Send a request to a specific endpoint and display the retrieved data with Angular

Trying to access an endpoint with a GET request and display the data on my webpage

<script type="text/javascript" src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>

<div ng-app="myApp" ng-controller="myCtrl">
  <p>Data is:</p>
  <h1>{{myData}}</h1>
</div>

<script>
  var app = angular.module('myApp', []);
  app.controller('myCtrl', function($scope, $http) {

    var promise = $http({
      method: 'GET',
      url: 'http://d.biossusa.com/api/distributor?key=*****',
      dataType: 'jsonp',
    });

    promise.success(function (data, status, header, config) {
      console.log("status is ", status);
      console.log(config.method + " data is: " + config.data);
      console.log("data is ", data);
      $scope.myData = response.data;

    });

  });
</script>

Encountering issues while trying to retrieve the data

https://i.sstatic.net/vmzJ4.png

Expected the data to be printed out!

https://jsfiddle.net/bheng/b3rgh92v/

Successfully retrieved data using curl for this URL: *****

https://i.sstatic.net/dbw0U.jpg

Seeking guidance on how to resolve angular related issue

Answer №1

Here are a few important observations to consider:

1): Ensure that you have included the reference to your script file in your HTML if you are using an external file to create an Angular module.

2): Avoid using 'response' in your assignment.

$scope.myData = response.data; // Since 'response' is undefined, it should be removed

Instead, it should be:

$scope.myData = data;

3) Lastly, verify that you have permission to call the endpoint. I encountered an error when attempting to call an HTTP endpoint from Plunker's HTTPS endpoint, so I modified the GET URL accordingly. After making these adjustments and testing your code on Plunker with a different URL, everything worked fine. You can view the updated code here.

Answer №2

  1. Adjust JsFiddle javascript Load type to No wrap - in <body>
  2. Delete the <script> tag from the javascript block
  3. Replace response.data with data
  4. Access JsFiddle through http as the endpoint only supports http

    var app = angular.module('myApp', []);
      app.controller('myCtrl', function($scope, $http) {

    var promise = $http({
          method: 'GET',
          url: 'http://d.biossusa.com/api/distributor?key=*****',
          dataType: 'jsonp',
        });

        promise.success(function (data, status, header, config) {
          console.log("status is ", status);
          console.log(config.method + " data is: " + config.data);
          console.log("data is ", data);
          $scope.myData = data;
        });    
      });

http://jsfiddle.net/b3rgh92v/15/

Answer №3

1) Start by removing script tags from your JavaScript code. If you want to incorporate angular code using script tags, make sure to include it in an HTML file as shown below. Also, consider keeping your angular code in a separate file for organization.

2) Due to the large amount of data, it may take some time to load and the success block can take approximately 30 seconds to execute. Similarly, when printing data in HTML using angular, it may also require a few seconds.

3) When assigning data to the scope, utilize $scope.myData = data; instead of $scope.myData = response.data;. This is because the data is received in the 'data' parameter, not within the 'response' object (which is not within the parameters).

4) Keep in mind that you cannot make HTTP calls while on an HTTPS domain in angular. To resolve this, load your 'jsfiddle' in HTTP so that you can successfully make HTTP calls.

Other than these adjustments, there doesn't seem to be anything wrong with your code. I have made some necessary changes which are visible in the code snippet below. You can view a working plnkr example here.

<!DOCTYPE html>
<html>

  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
  </head>

  <body>
   <div ng-app="myApp" ng-controller="myCtrl">

  <p>Data is:</p>
  <p>{{myData}}</p>

</div>
<script>
  var app = angular.module('myApp', []);
  app.controller('myCtrl', function($scope, $http) {

    $http({
      method: 'GET',
      url: 'http://d.biossusa.com/api/distributor?key=*****', 
      dataType: 'jsonp',
    }).then(function (successResponse) { 
      debugger 
      $scope.myData = JSON.stringify(successResponse.data);
            console.log("successResponse", successResponse.data);
        }, function (error) {
             $scope.myData = {};
             console.log('error',error)
        });

  });
  </script>
  </body>
</html>

The provided code functions correctly, but it's worth considering using then instead of success. The reasoning behind this change is explained below.

Implementation of success(): By looking at Angular's source code here, we can see that success is essentially:

promise.success = function(fn) {
// ...
promise.then(function(response) {
    fn(response.data, response.status, response.headers, config);
});
return promise;
};

Simply put, it is similar to then() but automatically deconstructs the response object. It serves as syntax sugar, providing a callback that receives the JSON object as its first argument without needing to access response.data directly. More information can be found in this source. Further details can easily be found through a quick internet search.

Answer №4

After pasting your example into a plunkr, everything seems to be working fine except for the AJAX request due to CORS restrictions.

You can view the plunkr example here.

Make sure to remove the <script> tags from your JavaScript window in the fiddle as well.

I examined your jsFiddle, disabled the JavaScript code, but there still seems to be an injector error showing up in the console, which is quite unusual.

Answer №5

Upon reviewing your code on Fiddle, I have noticed a couple of issues:

1. Angular module not found issue

In the example provided, you have added a <script> tag within a script section. There is no need to include another <script> tag in that section as it is already embedded inside one.

Additionally, your JavaScript code is set to run on the onload event, which causes the angular module to be unavailable during bootstrapping. To resolve this, change the setting to No wrap - in <body> under the JavaScript section at the top right corner.

2. Making requests from https server to http server

ERROR : Mixed Content: The page at 'https://jsfiddle.net/b3rgh92v/' was loaded over HTTPS, but requested an insecure XMLHttpRequest endpoint '*****'. This request has been blocked; the content must be served over HTTPS.

While it is possible to make https requests from a non-https server, making requests to a non-https server from an https server is prohibited. Therefore, all requests should be made from an https server only.

I have modified the URL to point to a different testing API on another https server, and it is functioning correctly.

You can view the updated code at https://jsfiddle.net/b3rgh92v/11/

Answer №6

Observations regarding the code on your JSFiddle:

  • Change the LOAD TYPE setting from onLoad to No wrap - in <head>.
  • You do not need to include jQuery as an External Resource in the fiddle.
  • Delete the start<script> and end</script> tags from the JAVASCRIPT section of your fiddle.
  • Since JSON executes over the http protocol, while JSFiddle runs on the https protocol, you may encounter errors if the code is executed on JSFiddle.

Mixed Content: The page at 'https://jsfiddle.net/bheng/b3rgh92v/' was loaded over HTTPS, but requested an insecure XMLHttpRequest endpoint '*****'. This request has been blocked; the content must be served over HTTPS.

Updated version of your JSFiddle: https://jsfiddle.net/b3rgh92v/9/

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Are you using yeoman with csslint in your project?

As a newcomer to grunt, I am facing challenges in integrating csslint to monitor my project while running "grunt serve" for csslinting. I am specifically struggling with disabling the adjoining classes warning since it is not relevant for IE6 compatibili ...

When validated, the Yup.date() function seamlessly converts a date into a string without including the timezone

Currently, I am integrating Yup with react-hook-form and have defined the following schema in Yup: const validationSchema = Yup.object({ installation: Yup.string().nullable().required("Required"), from_date: Yup.date() .max(new Date(), "Can ...

Exploring AngularJS and Jasmine for testing a factory component

I am currently learning about unit testing in AngularJS. I have a factory that I am trying to spy on using Jasmine, but I am having trouble figuring out the correct syntax for the test spec. Below is the code snippet for the factory: app.factory('ass ...

Using JavaScript's if-else statements is akin to a checkbox that is always in its

When working with checkboxes, I can retrieve the state (checked or unchecked) in the browser developer console using $("#blackbox").prop('checked')or $('#blackbox').is(':checked'). I have tried both methods. For example, if I ...

The result obtained from response.download() is saved as a blob that may contain undefined elements

I am in the process of developing a client-server certificate generator. In terms of the Backend, I have set up two endpoints: / This endpoint receives a JSON containing extracted data from inputs, sanitizes them, and determines if they are valid or not ...

Utilize jQuery to set a cookie, then apply the bodyclass retrieved from the cookie upon page

I have a button that changes the body class to .blackout For this, I am utilizing js-cookie library to manage cookies. The code snippet associated with my button is shown below: <script> $('#boToggle').on('click', function(e) { ...

How can I send a form without having the page reload using a combination of AJAX, PHP

I am struggling to submit a form without refreshing the page. I have tried using ajax as mentioned in some resources, but it's not working for me. What could be the issue? When I use the following code, everything works fine with PHP: document.getEl ...

PHP is throwing an error because of a missing parenthesis in the argument list

Displaying data from PHP with a tag, here is the code: echo '<a class="ui label" onclick="variant_desc('.$product_id.');"> '.$variant->Field1.' </a>'; When I click the function mentioned in the tag, I get the ...

A guide on getting the `Message` return from `CommandInteraction.reply()` in the discord API

In my TypeScript code snippet, I am generating an embed in response to user interaction and sending it. Here is the code: const embed = await this.generateEmbed(...); await interaction.reply({embeds: [embed]}); const sentMessage: Message = <Message<b ...

"Encountering a JavaScript issue while attempting to group items in a Kendo Grid

I'm encountering a problem with my Kendo grid that is populated with AJAX in an ASP.NET MVC view. When I attempt to group by the property FacturasCabecera.NFactura, I get a JavaScript error stating d.ArtFacturasCabecera is undefined, causing the Kendo ...

Clicking within the text activates the dropdown menu, but clicking outside the text does not

My custom drop down menu is not functioning properly. When I click on the text, it successfully links to another place, but when I click beside the text, it does not link. Can you please help me identify what's wrong here? Your assistance would be gre ...

Encountering a problem with the Laravel framework related to an 'illegal string offset' issue within the 'leave_form' array

As I work on the edit page for a leave application form, I encountered an issue when trying to update the form. The error message 'Illegal string offset 'leave_form' is displayed. My current setup involves the use of Vue.js and PHP. Despite ...

After refreshing the page, Google Chrome finally displays the CSS styles correctly

I'm currently working on a JavaScript script to showcase images on a webpage. These images are loaded using an AJAX request and a CSS style is directly applied using jQuery. The script functions correctly on Firefox, Opera, and IE, but Google Chrome i ...

Struggling to retrieve HttpResponse information while using AngularJS $http.post

In my VB.NET code behind, I am trying to return a custom object to an AngularJS HTTP Post request. Sometimes, the object can be very large, causing an OutOfMemoryException when trying to serialize it. To solve this issue, I am now using the JSON.NET packag ...

The functionality of the Express module in a Node.js environment is not functioning as

I am currently utilizing the 'express' module within Node JS following the example here Upon attempting to run the server and accessing 'localhost:8000', I encounter the following error: Error: No default engine was specified and no e ...

Tips for resolving the error message: React is not able to identify the `currentSlide` and `slideCount` prop on a DOM element

I recently implemented an image slider using "react-slick" in my next.js project. However, I encountered some warnings in the console related to the 'currentSlide' and 'slideCount' props on a DOM element. Warning: React does not recogni ...

Regular expressions can be used to remove specific parts of a URL that come before the domain name

Looking for some help with a javascript task involving regex and the split function. Here's what I need to achieve: Input: http://www.google.com/some-page.html Output: http://www.google.com I attempted the following code but unfortunately it didn&ap ...

Convert coordinates from X and Y within a rotated ImageOverlay to latitude and longitude

After going over all the details in Projection's documentation and conducting various trial and error tests, I have hit a roadblock in finding a solution to this particular issue. All the solutions I have come across assume the x and y coordinates ar ...

How to preselect an item in a RadioGroup

We are facing a challenge in setting a default value automatically for a RadioGroup upon page load. Despite the documentation mentioning a defaultValue property (https://material-ui.com/api/radio-group/), it does not seem to work as expected. We experimen ...

Encountering an issue while invoking the helper function in Vuejs

Main view: <script> import { testMethod1 } from "../helper"; export default { methods: { init(){ console.log("Res:", testMethod1()); } } } </script> Helper: import DataService from "../services/data. ...