Laravel + AngularJS 跨域资源共享(CORS)无法工作

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;
            }

           ...
    }

我的Angular模块还配置了:

.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状态有什么原因?
1个回答

0

Angular.js的$http服务将200到299之间的任何状态视为有效状态,您可以在$http源代码中看到; 这里这里我找不到硬编码的状态200。

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接