Laravel + AngularJS CORS 不起作用


Laravel + AngularJS CORS not working

我正在做一个AngularJS项目,现在在http://localhost,在http://api.localhost有一个laravel后端,两者都由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'];
}])

选项调用按预期返回:

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,并且角度向 JS 控制台抛出错误:

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

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

怎么办?

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

AngularJS在跨源请求中只接受200状态有什么原因吗?

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

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