【问题标题】:Laravel + AngularJS CORS not workingLaravel + AngularJS CORS 不工作
【发布时间】:2013-11-14 15:52:51
【问题描述】:

我正在创建一个 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,并且 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 状态是否有原因?

【问题讨论】:

    标签: javascript php angularjs nginx cors


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2014-06-01
      • 2017-09-10
      • 2015-04-12
      • 1970-01-01
      • 2016-02-14
      • 2016-05-26
      • 2015-05-16
      • 2017-02-13
      相关资源
      最近更新 更多