对于Angular和CORS的另一个问题抱歉,但我不能确定问题出在哪里。我的基本设置是纯角度的独立网站,因此没有Express或任何服务器端组件,与另一台服务器上的基于Java的API进行通信。该API使用JAX-RS构建,并位于JBoss 7.1.3应用程序服务器中。我可以访问angular和java的代码。带有授权标题的AngularJS CORS
在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的工作原理是通过提供一个返回令牌端点的用户名和密码的方式,此令牌然后被包含在每个后续请求的授权报头。该过程的第一部分工作正常,我可以提供有效的凭据并接收令牌,但随后的任何请求都不会起作用。因此,在我的Angular服务中,我有以下登录方法,它会获取一个令牌,然后尝试获取当前登录的用户。
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端点,并按照预期返回用户对象。
任何帮助将不胜感激!