AngularJS:在$ http.post请求之前的OPTIONS预检调用

时间:2013-12-19 00:57:21

标签: javascript http angularjs cors

我正在使用AngularJS v1.2.4。

我在Angular发送预检OPTIONS调用时遇到问题(Chrome将OPTIONS调用显示为'已取消')并通过以下方式解决了该问题:

$httpProvider.defaults.useXDomain = true;
delete $httpProvider.defaults.headers.common['X-Requested-With'];

这适用于我所有的资源调用,一切都很好。

现在我正在尝试实现身份验证,以及一个使用用户凭据向我的服务器发送POST请求的登录页面。我看到之前遇到的问题,但$资源调用仍然正常。

令人沮丧的是问题是间歇性地发生的;我将更改标题周围的一些选项,然后它会工作一段时间,并在没有任何代码更改的情况下再次停止工作。

我的服务器配置为CORS,并且可以与curl和其他REST客户端一起使用。这是一个例子:

curl -X OPTIONS -ik 'https://localhost:3001/authenticate' -H "Origin: https://localhost:8001"
HTTP/1.1 200 OK
content-type: application/json; charset=utf-8
content-length: 2
cache-control: no-cache
access-control-allow-origin: *
access-control-max-age: 86400
access-control-allow-methods: GET, HEAD, POST, PUT, DELETE, OPTIONS
access-control-allow-headers: Authorization, Content-Type, If-None-Match, Access-Control-Allow-Headers, Content-Type
access-control-expose-headers: WWW-Authenticate, Server-Authorization
set-cookie: session=Fe26.2**94705d49717d1273197ae86ce6661775627d7c6066547b757118c90c056e393b*2KYqhATojPoQhpB2OwhDwg*W9GsJjK-F-UPqIIHTBHHZx1RXipo0zvr97_LtTLMscRkKqLqr8H6WiGd2kczVwL5M25FBlB1su0JZllq2QB-9w**5510263d744a9d5dc879a89b314f6379d17a39610d70017d60acef01fa63ec10*pkC9zEOJTY_skGhb4corYRGkUNGJUr8m5O1US2YhaRE; Secure; Path=/
Date: Wed, 18 Dec 2013 23:35:56 GMT
Connection: keep-alive

这是$ http.post电话:

var authRequest = $http.post('https://' + $location.host() + ':3001/authenticate', {email: email, password: password});

当我的应用程序调用有效时,这就是OPTIONS请求的样子:

enter image description here

当它不起作用时,这是OPTIONS请求:

enter image description here

看起来缺少一大堆标题属性。有没有人遇到类似的问题?

编辑:

只是澄清一下,当它不起作用时,请求永远不会进入服务器 - 它会立即在浏览器中中止。

enter image description here

在Firebug中,请求标头为:

OPTIONS /authenticate HTTP/1.1
Host: localhost:3001
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:25.0) Gecko/20100101 Firefox/25.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.91,en-GB;q=0.82,fr-FR;q=0.73,fr;q=0.64,utf-8;q=0.55,utf;q=0.45,de-DE;q=0.36,de;q=0.27,en-sg;q=0.18,en-ca;q=0.09
Accept-Encoding: gzip, deflate
Origin: https://localhost:8001
Access-Control-Request-Method: POST
Access-Control-Request-Headers: content-type
Proxy-Authorization: Basic cGF0cmljZUB6b25nLmNvbTpjaGFuZ2VtZQ==
Connection: keep-alive
Pragma: no-cache
Cache-Control: no-cache

enter image description here

更新

我认为,通过将主机更改为不存在的服务器,我已经消除了服务器可能存在的问题。仍然看到相同的行为。

以下是一些代码:

App.services.factory('AuthService', function ($http, $location, $q) {

    var currentUser;

    return {
        authenticate: function (email, password) {

            //promise to return
            var deferred = $q.defer();

            var authRequest = $http.post('https://this.does.not.exist.com:3001/authenticate', {email: email, password: password});

            authRequest.success(function (data, status, header, config) {
                currentUser = data;
                console.log('currentUser in service set to:');
                console.log(currentUser);
                //resolve promise
                deferred.resolve();
            });

            authRequest.error(function (data, status, header, config) {
                console.log('authentication error');
                console.log(status);
                console.log(data);
                console.log(header);
                console.log(config);

                //reject promise
                deferred.reject('authentication failed..');
            });

            return deferred.promise;
        },
        isAuthenticated: function () {
            return currentUser !== undefined;
        }
    };
});

和HTTP配置:

App.config(['$httpProvider', function ($httpProvider) {

    $httpProvider.defaults.useXDomain = true;
    //$httpProvider.defaults.headers.common = {};

    console.log('logging out headers');
    console.log($httpProvider.defaults);
    console.log($httpProvider.defaults.headers.common);
    console.log($httpProvider.defaults.headers.post);
    console.log($httpProvider.defaults.headers.put);
    console.log($httpProvider.defaults.headers.patch);
    console.log('end logging out headers');

    $httpProvider.defaults.headers.common = {Accept: "application/json, text/plain, */*"};
    $httpProvider.defaults.headers.post = {"Content-Type": "application/json;charset=utf-8"};

    console.log('after: logging out headers');
    console.log($httpProvider.defaults.headers.common);
    console.log($httpProvider.defaults.headers.post);
    console.log($httpProvider.defaults.headers.put);
    console.log($httpProvider.defaults.headers.patch);
    console.log('after: end logging out headers');

    $httpProvider.interceptors.push(function ($location, $injector) {
        return {
            'request': function (config) {

                console.log('in request interceptor!');

                var path = $location.path();
                console.log('request: ' + path);

                //injected manually to get around circular dependency problem.
                var AuthService = $injector.get('AuthService');
                console.log(AuthService);
                console.log(config);

                if (!AuthService.isAuthenticated() && $location.path() != '/login') {
                    console.log('user is not logged in.');
                    $location.path('/login');
                }

                //add headers
                console.log(config.headers);
                return config;
            }
        };
    });
}]);

3 个答案:

答案 0 :(得分:13)

这感觉可能与您在本地主机上命中https端点的事实有关。这意味着您可能正在使用某种自签名SSL证书,这可能意味着Chrome认为它不受信任。

我首先尝试直接转到/ authenticate端点,看看Chrome是否会向您发出有关不受信任证书的警告。看看是否接受该警告。

否则,当您在本地进行测试时,您可以只点击一个http端点并查看是否可以解决问题?

答案 1 :(得分:9)

非常感谢Michael Cox for pointing me in the right direction。我接受了他的回答,因为它引导我找到了解决方案,但这里有更多细节:

查看https问题,我发现:

我的问题虽然略有不同。在我按照上面链接中的说明操作后,它仍然无法正常工作。我仔细阅读了Chrome“不信任”消息,它类似于“您正在尝试访问mylocalhost.com,但服务器将其表示为”。

事实证明,我匆忙创建的自签名证书是“server.crt”,应该是“mylocalhost.crt”

答案 2 :(得分:7)

您不能与allow-credentials一起Access-Control-Allow-Origin: *

  

重要说明:在响应凭证请求时,服务器必须指定域,并且不能使用通配符。

关于GET请求,如果他们没有特殊的标题,他们就不需要预检等。

来源:Mozilla Developer Network。 (网上最好的CORS链接!)