Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSONP request gives 404 in Angular app

I'm trying to get some data from an API with a JSONP request, but I get a 404 every time. I would assume my URL is wrong, but I can hit the URL manually in Chrome and get the desired response. My $http.jsonp request always errors with a 404 showing up in my console.log in the error callback.

Here's the code that makes the request:

$scope.fetchDefaultLabel = function () {
      // This code will eventually set the label to the site name when the endpoint field blurs.
      // Currently not working properly.
      if ($scope.endpoint) {
        var baseUrl = $scope.endpoint.split('/')[2];
        var siteNameUrl = 'http://' + baseUrl + '/api/sitename.json?callback=JSON_CALLBACK';
        console.log(siteNameUrl);
        $http.jsonp(siteNameUrl)
          .success(function(data, status, headers, config) {
            $scope.label = data;
          })
          .error(function(data, status, headers, config) {
            console.log('Data: ' + data);
            console.log('Status: ' + status);
            console.log('Headers: ' + headers);
            console.log('Config: ' + config);
          });
      }
    };

Network panel of Chrome Dev Tools shows a 200 response for the request with the response body I would expect, but that's not getting to Angular for whatever reason.

like image 988
raddevon Avatar asked Jun 06 '14 01:06

raddevon


People also ask

What is Jsonp in angular?

What is JSONP ? JSONP is a method of performing API requests which go around the issue of CORS . This is a security measure implemented in all browsers that stops you from using an API in a potentially unsolicited way and most API s, including the iTunes API , are protected by it.

How does Jsonp request work?

It works by dynamically adding a <script> tag to the DOM and calling a predefined function with the remote web service's JSON data as the parameter. The <script> tag is not subject to the same origin policy and therefore can request content cross-domain.

Does Angular JS HTTP service provide Jsonp functionality?

Angular Jsonp It provides the normal get , post and other functions mapped to http methods. It also provides the function that we'll need: jsonp . The client script also requires that we specify the callback to send data to.

Which is added to the DOM to create Jsonp request?

Script element injection For each new JSONP request, the browser must add a new <script> element, or reuse an existing one. The former option—adding a new script element—is done via dynamic DOM manipulation, and is known as script element injection.


1 Answers

After talking with some back-end developers, it appears the API I am using does not support JSONP. This is the reason I was getting a 404 on that request.

like image 163
raddevon Avatar answered Sep 19 '22 01:09

raddevon