我正在创建一个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状态?
最佳答案
原文链接:/nginx/434778.html