简体   繁体   中英

$http - Headers not returning - AngularJS

I have an Angular Service I'm trying to set up to retrieve data from a node server that serving JSON files to the application. I've checked the node server URL's and they're all outputting JSON like they should be, but Angular appears to be unable to get them due to the HTTP headers. From some googling this looks like a common problem, I'm just not sure how or even if there's a work around?

eventsApp.factory('eventData', function($http, $log) {
    return {
        getEvent: function(successcb) {
            $http({method: 'GET', url: 'http://localhost:8000/data/event/1'}).
                success(function(data, status, headers, config){
                    successcb(data);
                }).
                catch(function(data, status, headers, config){
                    $log.warn(data, status, headers, config);
                })
        }
    }
});

In the console I'm getting the following warning from the catch:

Object { data: null, status: 0, headers: headersGetter/<(), config: Object, statusText: "" } undefined undefined undefined

From the documentation

// Simple GET request example:
$http({
  method: 'GET',
  url: '/someUrl'
}).then(function successCallback(response) {
    // this callback will be called asynchronously
    // when the response is available
  }, function errorCallback(response) {
    // called asynchronously if an error occurs
    // or server returns response with an error status.
  });

The response object has these properties:

  • data – {string|Object} – The response body transformed with the transform functions.
  • status – {number} – HTTP status code of the response.
  • headers – {function([headerName])} – Header getter function.
  • config – {Object} – The configuration object that was used to generate the request.
  • statusText – {string} – HTTP status text of the response.

So you should be able to get the interested header using:

response.headers('header-name')

Aslo according to your response's log: the result.data is null. So you should check the Network tab of Chrome Dev Tools and examine the aqtual http response from the server.

The status 0 indicates the possible CORS problem. So if your angular application is hosted on another host or port than server to which you trying to send the http request (localhost:8000 in your case), then you shoud configure the SERVER to allow CORS requests.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM