【问题标题】:Angularjs: Why does adding an authorization header cause a -1 status response?Angularjs:为什么添加授权标头会导致-1状态响应?
【发布时间】:2017-03-04 00:16:55
【问题描述】:

我有一个预先存在的角度代码,可以从 API 获取数据。我正在尝试向请求添加身份验证令牌。

首先我尝试了一个简单的例子

.factory('getDep', [
        '$resource', function($resource) {
            return $resource('/ContactsDatabaseAPI/deps/:id', { id: '@id' }, {
                query: {
                    method: 'GET',
                    isArray: false,
                    headers: {
                        'Authorization': 'Bearer ' + token
                    }
                },
                create: {
                    method: 'POST'
                },
                update: {
                    method: 'PUT'
                },
                remove: {
                    method: 'DELETE'
                }
            });
        }

当 GET 调用被触发并在 Chrome 中按 F12 时,我收到以下错误消息:

angular.js:11821 OPTIONS http://localhost:56057/ContactsDatabaseAPI/deps net::ERR_CONNECTION_RESET

-1 的返回状态,并且没有调用到服务器端的迹象。

没有标题行,它工作正常。

如果我尝试在 Postman 中使用标头中相同的 Authorization 值进行 GET 调用,这也可以正常工作。

我也尝试在 httpInterceptor 中添加标头并得到相同的结果:

config.headers = config.headers || {};
config.headers.Authorization = 'Bearer ' + authData.token;

我尝试过的其他事情:

  • 随机标题名称会导致同样的问题。
  • 我添加了 'Content-Type' = 'text/plain; charset=utf-8' 作为标题。这对结果没有变化

我正在使用角度 1.5.6

【问题讨论】:

标签: angularjs asynchronous http-post restier


【解决方案1】:

试试这个(在控制器中):

$http.defaults.headers.common.Authorization = 'Bearer' + 令牌;

【讨论】:

  • 我们在应用程序中使用了几个不同的 API。我相信添加这将意味着令牌附加到所有 API 调用。
  • 它和写的一样,不同的是你强制了http头。 (您可以在每次调用服务时使用它)
  • 我还是试了一下。我收到相同的错误消息
  • 你在使用 oauth 吗?还是您自己的 API? (确保服务器端的 OPTIONS 和 GET 请求)
【解决方案2】:

我已经解决了我的问题,感谢@Mourad-Idrissi 为我指明了正确的方向。

它之前工作的原因是在 API 运行之前没有进行飞行前检查。当我添加标头时,这改变了客户端与 API 通信的方式。现在有一个对导致错误的 API 的 OPTIONS 调用。由于域不同,这让我进入了 CORS 的世界。

通过在我的后端 Web API 中的 Application_BeginRequest() 方法中添加以下内容,Pre-flight 现在通过并且我的应用程序继续。

if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
{
    HttpContext.Current.Response.AddHeader("Cache-Control", "no-cache");
    HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST");
    HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept, Authorization");
    HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
    HttpContext.Current.Response.End();
}

【讨论】:

    猜你喜欢
    • 2014-05-06
    • 2019-08-19
    • 2020-09-01
    • 2018-03-10
    • 1970-01-01
    • 1970-01-01
    • 2019-04-20
    • 2017-05-18
    • 2017-06-10
    相关资源
    最近更新 更多