【发布时间】:2014-01-02 05:50:59
【问题描述】:
我正在使用 angular 1.2 编写应用程序,我正在尝试在本地 glassfish 3.1 上调用 REST API。 我说得对:
app.factory("shopModel", function($resource){
return $resource('http://localhost:8080/Schedule-service/shops', {}, {
query:
{method:'GET',
headers: {'Content-Type': 'application/json'}
params:{}}
});
});
但我的 chrome 出现错误。
XMLHttpRequest cannot load http://localhost:8080/Schedule-service/shops. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access.
我将此代码添加到我的应用配置中,但这没有帮助:
app.config(['$httpProvider', function($httpProvider) {
$httpProvider.defaults.useXDomain = true;
delete $httpProvider.defaults.headers.common['X-Requested-With'];
}]);
我不知道该怎么办。我会感谢每一个提示。
编辑。 我将 headers_module 添加到我的 apache wamp 中。我在我的 httpd.conf 文件中添加了这个:
<IfModule mod_headers.c>
Header set Access-Control-Allow-Origin: *
</IfModule>
但还是不行。有什么建议吗??
编辑2。 好的,我解决了。我已将此过滤器添加到我的 Spring 网络中:
public class CorsFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
response.addHeader("Access-Control-Allow-Origin", "*");
response.addHeader("Access-Control-Allow-Methods",
"GET, POST, PUT, DELETE, OPTIONS");
response.addHeader("Access-Control-Allow-Headers",
"origin, content-type, accept, x-requested-with, sid, mycustom, smuser");
filterChain.doFilter(request, response);
}
}
谢谢昆汀。
【问题讨论】:
-
你能解释一下你是如何解决你的错误的吗?我有类似的问题尝试了 https.conf 解决方案,htaccess 解决方案但没有成功,我正在使用启用 headers_module 的 wamp 服务器。
-
请问,我在哪里添加 CORS 过滤器类?我可以让我的应用程序类扩展它吗?