我无法在我的服务器上启用 CORS 并结合使用 AngularJS。我正在使用 Angular 1.2.16,这是我的服务器配置:
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 () {}));
因为此请求不使用自定义 header 。
当我之后尝试请求以下内容时:
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()
}
}
});
}]);
我得到一个 401 Unauthorized
在 balanceUrl 上。
在我设置的配置中:
$httpProvider.defaults.useXDomain = true;
delete $httpProvider.defaults.headers.common['X-Requested-With'];
我什至试着把 $http.defaults.headers.common.Authorization = Auth.getAuthToken();
在 $resource
之前在Balance
资源工厂,但这没有帮助。
发送到预检的 header OPTIONS
请求没有 Authorization
标题,无论我使用什么方法。这些是预检的请求 header 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
有什么建议吗?
最佳答案
据我所知,您不能将 Access-Control-Allow-Origin "*"
与 Access-Control-Allow-Credentials "true"
一起使用。
关于javascript - AngularJS CORS 请求自定义 header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24363907/