javascript – Laravel AngularJS 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,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,Authorization
Access-Control-Allow-Methods:GET,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.仍然是相同的取消状态.但当我将状态调整为200时,瞧!该请求按预期工作.

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

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

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

相关文章

文章浏览阅读3.7k次,点赞2次,收藏5次。Nginx学习笔记一、N...
文章浏览阅读1.7w次,点赞14次,收藏61次。我们在使用容器的...
文章浏览阅读1.4k次。当用户在访问网站的过程中遇到404错误时...
文章浏览阅读2.7k次。docker 和 docker-compose 部署 nginx+...
文章浏览阅读1.3k次。5:再次启动nginx,可以正常启动,可以...
文章浏览阅读3.1w次,点赞105次,收藏182次。高性能:Nginx ...