在 angularjs 中访问自定义 http 响应标头 [英] Accessing custom http response headers in angularjs

查看:37
本文介绍了在 angularjs 中访问自定义 http 响应标头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试访问标题错误详细信息",正如您在浏览器网络检查器(上面的链接)中看到的那样,标题被返回.在服务器方面,我还向Access-Control-Expose-Headers"添加了自定义标头,以允许跨域请求,因为这被建议用于解决其他问题.

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'));

这只会输出:内容类型:应用程序/json"错误详细信息:空

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?

推荐答案

我认为您走对了路.要访问自定义标头,您的服务器需要设置这个特殊的 Access-Control-Expose-Headers 标头,否则您的浏览器将只允许访问 Mozilla 文档.

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.

在您的屏幕截图中,响应中不存在此类标头.您应该查看后端,以便此 cors 标头也出现在响应中.

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.

这篇关于在 angularjs 中访问自定义 http 响应标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆