很抱歉又问了一个关于 Angular 和 CORS 的问题,但我无法确定问题出在哪里。我的基本设置是一个纯 Angular 的独立网站,因此没有 Express 或任何服务器端组件,它与另一台服务器上基于 Java 的 API 通信。 API 是使用 JAX-RS 构建的,位于 JBoss 7.1.3 应用程序服务器中。我可以访问 angular 和 java 的代码。
在 API 端,使用如下所示的流行 thetransactioncompany CORS 过滤器启用 CORS。
<filter>
<filter-name>CORS</filter-name>
<filter-class>com.thetransactioncompany.cors.CORSFilter</filter-class>
<init-param>
<param-name>cors.supportedMethods</param-name>
<param-value>GET, POST, HEAD, PUT, DELETE, OPTIONS</param-value>
</init-param>
<init-param>
<param-name>cors.supportedHeaders</param-name>
<param-value>Origin, Accept, Content-Type, X-Requested-With, Cookie,content-type</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CORS</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
API 的工作方式是通过向返回 token 的端点提供用户名和密码,然后将此 token 包含在每个后续请求的授权 header 中。该过程的第一部分工作正常,我可以提供有效的凭证并接收 token ,但随后的任何后续请求都无法正常工作。所以在我的 Angular 服务中,我有以下登录方法,它获取一个 token ,然后尝试获取当前登录的用户。
login: function(username, password){
var deferred = $q.defer();
$http({
method: 'POST',
url: 'http://localhost:8080/website-api/rest/account/token',
headers: {'Content-Type': 'application/x-www-form-urlencoded', 'Accept': 'application/json'},
transformRequest: function(obj) {
var str = [];
for(var p in obj){
str.push(encodeURIComponent(p) + '=' + encodeURIComponent(obj[p]));
}
return str.join('&');
},
data: {username: username, password: password }
})
.success(function(token) {
$log.info(token.jwt);
var requestConfig = {
headers: {
'Authorization': token.jwt,
'Accept': 'application/json',
'X-Testing': 'Testing'
}
};
$http.get('http://localhost:8080/website-api/rest/users/current', requestConfig)
.success(function(user) {
$log.info('Retrieved User');
user.sessionToken = token.jwt;
deferred.resolve(user);
})
.error(function(data, status, headers, config) {
$log.info(data);
$log.info(status);
$log.info(headers);
$log.info(config);
});
})
.error(function(data, status, headers, config) {
$log.info(data);
$log.info(status);
$log.info(headers);
$log.info(config);
});
return deferred.promise;
}
第一个请求完美运行,第二个请求失败并出现错误:
XMLHttpRequest cannot load http://localhost:8080/website-api/rest/users/current. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:9000' is therefore not allowed access.
我无法确定是 API 上的 CORS 过滤器设置是我的问题的原因,还是我在从 Angular 发送请求时没有正确执行某些操作。我怀疑它是 Angular,因为我可以使用第三方服务 Postman 和 Hurl.it 来测试我的 API 端点,它们会按预期返回用户对象。
任何帮助将不胜感激!
最佳答案
基于阅读这篇 post 的直觉,我注意到我不仅在接受的 header 列表中定义了两次 Content-Type
,而且我没有将 Authorization
设置为允许的 header 。 CORS 过滤器拒绝任何包含不允许的 header 的传入请求,导致我的 403 错误。
关于java - 带有授权 header 的 AngularJS CORS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26634771/