7

我正在制作一个 AngularJS 项目,现在http://localhost使用 laravel 后端http://api.localhost,两者都由 nginx 服务器提供服务。

在发出 $http.post 请求时,Angular 首先进行 CORS OPTIONS 调用,并且我已将我的 nginx 服务器配置为使用正确的标头进行响应:

    location / {
            add_header "Access-Control-Allow-Origin" "*";
            add_header "Access-Control-Allow-Credentials" "true";
            add_header "Access-Control-Allow-Methods" "GET,POST,DELETE,PUT,OPTIONS";
            add_header "Access-Control-Allow-Headers" "Keep-Alive,User-Agent,If-Modified-Since,Cache-Control,Content-Type,Authorization";
            add_header "Access-Control-Max-Age" "1728000";

            if ($request_method = 'OPTIONS') {
                    return 204;
            }


            #try_files $uri $uri/ /index.html;
            try_files $uri /index.php?$query_string;
    }

    location = /index.php {

            add_header "Access-Control-Allow-Origin" "*";
            add_header "Access-Control-Allow-Credentials" "true";
            add_header "Access-Control-Allow-Methods" "GET,POST,DELETE,PUT,OPTIONS";
            add_header "Access-Control-Allow-Headers" "Keep-Alive,User-Agent,If-Modified-Since,Cache-Control,Content-Type,Authorization";
            add_header "Access-Control-Max-Age" "1728000";

            if ($request_method = 'OPTIONS') {
                    return 204;
            }

           ...
    }

我的角度模块还配置有:

.config(['$httpProvider', function($httpProvider) {
    $httpProvider.defaults.useXDomain = true;
    delete $httpProvider.defaults.headers.common['X-Requested-With'];
}])

OPTIONS 调用按预期返回:

Access-Control-Allow-Credentials:true
Access-Control-Allow-Headers:Keep-Alive,User-Agent,If-Modified-Since,Cache-Control,Content-Type,Authorization
Access-Control-Allow-Methods:GET,POST,DELETE,PUT,OPTIONS
Access-Control-Allow-Origin:*
Access-Control-Max-Age:1728000
Connection:keep-alive
Date:Mon, 04 Nov 2013 02:14:16 GMT
Server:nginx/1.2.6 (Ubuntu)

但是我进行的后续 POST 调用失败,状态为 CANCELED,并且 Angular 向 JS 控制台抛出错误:

`XMLHttpRequest cannot load http://api.localhost/users/accesstokens. Origin http://localhost is not allowed by Access-Control-Allow-Origin.`

我昨晚熬夜并得到了这个工作,但是当我今天再次尝试时,它又回到了原点。最糟糕的问题!

做什么?

编辑:我发现了问题,但我仍然不明白。我查看了我的 nginx 访问日志,发现 POST 请求实际上是在访问服务器,即使状态为 CANCELED。我还看到响应是 401。在我的请求正确后,响应是 201。仍然是相同的 CANCELED 状态。但是当我将状态调整为 200 时,瞧!该请求按预期工作。

AngularJS 在跨域请求中只接受 200 状态是否有原因?

4

1 回答 1

0

Angular.js $http 服务认为 200 到 299 之间的任何状态都是有效的,你可以在 $http 源代码中看到它;在这里这里,我在其他任何地方都找不到硬编码的状态 200。

尽管有 Chrome 控制台消息,但问题可能是 Alistair Robinson在这篇文章中指出的问题 检查您的 nginx 是否已更新到最新的稳定版本,然后检查它是否正确发送“Content-Length”标头,如果不是,我'将使用 Alistair 解决方案手动填充 Content-Length 标头。

于 2013-12-05T01:36:19.270 回答