我在與AngularJS結合使用我的服務器上啓用CORS時遇到問題。我採用了棱角分明1.2.16,這是我的服務器配置:AngularJS CORS請求自定義標題
Header set Access-Control-Allow-Origin "*"
Header set Access-Control-Allow-Headers "Content-Type, X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Date, X-Api-Version, X-File-Name, Authorization"
Header set Access-Control-Allow-Methods "POST, GET, PUT, DELETE, OPTIONS"
Header set Access-Control-Allow-Credentials "true"
我可以使用以下請求:
$http.post(configuration.authUrl, {username: 'username', password: 'password'})
.success(function (data) {
$cookieStore.put(configuration.sessionName, {
token: data.authenticationToken,
user: data.user
});
})
.error(function() {}));
,因爲這要求不使用自定義標題。
當我後來嘗試請求如下: Balance.get()
與其餘爲:
angular.module('portalApp')
.factory('Balance', ['$resource', 'Auth', 'configuration', function ($resource, Auth, configuration) {
return $resource(configuration.balanceUrl, {}, {
get: {
method: 'GET',
isArray: false,
headers: {
Authorization: Auth.getAuthToken()
}
}
});
}]);
我在balanceUrl得到401 Unauthorized
。
在配置我已經把:
$httpProvider.defaults.useXDomain = true;
delete $httpProvider.defaults.headers.common['X-Requested-With'];
我甚至試圖把$http.defaults.headers.common.Authorization = Auth.getAuthToken();
的$resource
之前在Balance
資源工廠,但沒有幫助。
無論使用什麼方法,發送到預檢OPTIONS
請求的標頭都沒有Authorization
標頭。這些是預檢OPTIONS
請求的請求標頭。
OPTIONS /api/v1.0/user/orders HTTP/1.1
Host: host
Connection: keep-alive
Cache-Control: no-cache
Access-Control-Request-Method: GET
Pragma: no-cache
Origin: origin
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.153 Safari/537.36
Access-Control-Request-Headers: accept, authorization
Accept: */*
Referer: referer
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8
有什麼建議嗎?
是的,你不能,http:// stackoverflow。com/a/19744754/101662 – Oliver