简体   繁体   English

由于CORS,无法连接到Java中的Web服务

[英]Can't connect to web service in Java due to CORS

I have created a filter like this and I configured it in the web.xml. 我已经创建了这样的过滤器,并在web.xml中对其进行了配置。 I manage to retrieve data with simple GET methods, but when trying to POST a new resource it fails. 我设法使用简单的GET方法检索数据,但是在尝试发布新资源时失败。 I am using AngularJS and I get this in the console. 我正在使用AngularJS,并且可以在控制台中找到它。 I haven't fully understood what CORS is, but from what I have read it seems like there is a "pre-flight" request (OPTIONS method?). 我还没有完全理解CORS是什么,但是从我阅读的内容来看,似乎有一个“飞行前”请求(OPTIONS方法?)。 I don't know what I miss, how can I fix it? 我不知道自己想念什么,如何解决? This is the error that I get: 这是我得到的错误:

Origin http://localhost is not allowed by Access-Control-Allow-Origin.

Code: 码:

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    final HttpServletResponse httpResponse = (HttpServletResponse) response;
    httpResponse.addHeader("Access-Control-Allow-Origin", "*");
    httpResponse.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
    httpResponse.addHeader("Access-Control-Allow-Headers", "Authorization, X-Requested-With, Content-Type");

    chain.doFilter(request, response);
}

You have to add some settings in you web.xml. 您必须在web.xml中添加一些设置。 Here is a link that should help you http://software.dzhuvinov.com/cors-filter-installation.html 这是一个应该对您有帮助的链接http://software.dzhuvinov.com/cors-filter-installation.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM