Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
385 views
in Technique[技术] by (71.8m points)

javascript - Accessing custom http response headers in angularjs

Response from server

I am trying to access the header 'error-detail' as you can see in the browser network inspector (link above), the header gets returned. Server-wise I have also added the custom header to the 'Access-Control-Expose-Headers' to allow cross-domain requests as this was suggested to be the fix on other questions.

Below is the request to the server along with the success/error callbacks.

this.signon = function (request, onComplete, onError) {
    console.log("Calling server with 'login' request...");

    return $http.post("http://localhost:8080/markit-war/services/rest/UserService/login/", request)
        .then(onComplete, onError);
};

var onLookupComplete = function(response) {
    if (response.data.username)
    {
        //If user is returned, redirect to the dashboard.
        $location.path('/dashboard');
    }

    $scope.username = response.data.username;
};

var onError = function(response) {
    $scope.error = "Ooops, something went wrong..";
    console.log('error-detail: ' + response.headers('error-detail'));
};

When I try access the response header as seen below:

    console.log(response.headers());
    console.log('error-detail: ' + response.headers('error-detail'));

This only outputs: content-type: "application/json" error-detail: null

Is there a reason why the error-detail header is not being mapped over to the response object?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I think you are on the right track. To have access to custom headers, your server needs to set this special Access-Control-Expose-Headers header, otherwise your browser will only allow access to 6 predefined header values as listed in the Mozilla docs.

In your screenshot such a header is not present in the response. You should have a look at the backend for this cors header to also be present in the response.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...