Laravel + AngularJS CORS无效

时间:2013-11-04 02:29:25

标签: javascript php angularjs nginx cors

我正在制作一个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'];
}])

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,而角度则向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.仍然是相同的取消状态。但当我将状态调整为200时,瞧!该请求按预期工作。

AngularJS是否只接受跨源请求中的200状态?

1 个答案:

答案 0 :(得分:0)

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

尽管有Chrome控制台消息,但问题可能出在Alistair Robinson身上points in this post 检查你的nginx是否更新到最新的稳定版本,然后检查它是否正确发送'Content-Length'标题,如果不是,我将使用Alistair解决方案手动填充Content-Length标题。