我正在尝试调试我的网络应用程序, 我有一个 POST 请求。 (使用 ajax,使用 xhrFields: { withCredentials: true } )。数据类型是“application/json”,我的服务器是 tomcat,我将“Access-Control-Allow-Origin” header 手动设置为“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 header “Access-Control-Allow-Origin”与“http://localhost:8080”不匹配)。
提前致谢!
最佳答案
如果您想要一个适用于所有请求的配置,请在您的 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 {
}
}
关于java - 手动执行 CORS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42653355/