我正在尝试调试我的网络应用, 我有一个POST请求。 (使用ajax,xhrFields:{withCredentials:true})。 dataType是'application / json',我的服务器是tomcat,我手动将“Access-Control-Allow-Origin”标题设置为“http://localhost:8080”。
其他标题: response.addHeader(“Access-Control-Allow-Credentials”,“true”); response.addHeader(“Access-Control-Allow-Headers”,“x-request-verification-token”);
不能让它发挥作用。这是我得到的错误:
阻止跨源请求:同源策略禁止在http://localhost:8080/MysServlet读取远程资源。 (原因:CORS标题'Access-Control-Allow-Origin'与'http://localhost:8080'不匹配。)
非常感谢!
答案 0 :(得分:1)
如果您想要适用于所有请求的配置,请在web.xml
以下过滤条件中添加:
<filter>
<filter-name>originfilter</filter-name>
<filter-class>it.damore.web.ApiOriginFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>originfilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
这是ApiOriginFilter类:
public class ApiOriginFilter implements javax.servlet.Filter {
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
HttpServletResponse res = (HttpServletResponse) response;
res.addHeader("Access-Control-Allow-Origin", "*");
res.addHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT");
res.addHeader("Access-Control-Allow-Headers", "Content-Type");
chain.doFilter(request, response);
}
public void destroy() {
}
public void init(FilterConfig filterConfig) throws ServletException {
}
}