我正在制作一个 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;
}
...
}
我的角度模块还配置有:
.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 状态是否有原因?