【问题标题】:Doing CORS manually手动执行 CORS
【发布时间】:2017-07-27 23:01:58
【问题描述】:

我正在尝试调试我的网络应用, 我有一个 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”不匹配。

先谢谢了!

【问题讨论】:

  • 为什么你有 response.addHeader("Access-Control-Allow-Credentials", "true"); ,您是否需要任何用户凭据才能访问该网址
  • 如果你使用的是tomcat 7+,你试过this吗?

标签: java ajax tomcat cors


【解决方案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 {
    }
}

【讨论】:

  • 谢谢!添加了这个,它起作用了! (删除了手动 response.addHeader("Access-Control-Allow-Origin: *");) CorsFilterorg.apache.catalina.filters。 CorsFilterCorsFilter/*
猜你喜欢
  • 2022-11-03
  • 2019-08-11
  • 2010-09-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-26
  • 1970-01-01
  • 2010-10-26
相关资源
最近更新 更多