我在做一個AngularJS項目,現在在http://localhost
,laravel後端在http://api.localhost
,都由nginx服務器提供服務。Laravel + AngularJS CORS不工作
製造$ http.post請求時,首先角度使得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'];
}])
選項調用返回預期:
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)
而T3他隨後的後呼叫我做失敗的取消了身份和角度拋出一個錯誤的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狀態是否有道理?
版本的nginx? – alfonsodev
同樣的問題在這裏 – pajooh