Cha*_*eph 7 javascript php nginx cors angularjs
我正在制作一个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;
}
...
}
Run Code Online (Sandbox Code Playgroud)
我的角度模块也配置有:
.config(['$httpProvider', function($httpProvider) {
$httpProvider.defaults.useXDomain = true;
delete $httpProvider.defaults.headers.common['X-Requested-With'];
}])
Run Code Online (Sandbox Code Playgroud)
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)
Run Code Online (Sandbox Code Playgroud)
但随后的POST调用失败,状态为CANCELED,angular会向JS控制台抛出错误:
`XMLHttpRequest cannot load http://api.localhost/users/accesstokens. Origin http://localhost is not allowed by Access-Control-Allow-Origin.`
Run Code Online (Sandbox Code Playgroud)
我昨晚熬夜并且工作得很好,但是当我今天再次尝试时,它又回到了原点.最糟糕的问题!
做什么?
编辑:我发现了问题,但我仍然不明白.我查看了我的nginx访问日志,并看到POST请求实际上已经命中服务器,即使状态为CANCELED.我也看到响应是401.在我的请求正确后,响应是201.仍然是相同的取消状态.但当我将状态调整为200时,瞧!该请求按预期工作.
AngularJS是否只接受跨源请求中的200状态?
归档时间: |
|
查看次数: |
1552 次 |
最近记录: |