angularjs Angular CORS '访问控制-允许-原点'问题

lx0bsm1f  于 2022-10-31  发布在  Angular
关注(0)|答案(2)|浏览(174)

我在tomcat 7.0.59上的CORS过滤器看起来像这样:

<filter>
    <filter-name>CorsFilter</filter-name>
    <filter-class>org.apache.catalina.filters.CorsFilter</filter-class>
    <init-param>
        <param-name>cors.allowed.headers</param-name>
        <param-value>accept, content-type, origin, if-match, if-non-match</param-value>
    </init-param>
    <init-param>
        <param-name>cors.allowed.methods</param-name>
        <param-value>GET, HEAD, OPTIONS, POST, DELETE, PUT</param-value>
    </init-param>
    <init-param>
        <param-name>cors.exposed.headers</param-name>
        <param-value>ETag, Link</param-value>   
    </init-param>
    <init-param>
      <param-name>cors.allowed.origins</param-name>
      <param-value>http://153.57.146.93,http://localhost:7777,http://localhost:9090</param-value>  
</filter>
<filter-mapping>
    <filter-name>CorsFilter</filter-name>
    <url-pattern>/*</url-pattern>    
</filter-mapping>

我试图从localhost:9090在Chrome访问服务器,我得到:请求的资源上不存在“Access-Control-Allow-Origin”标头。我的CORS筛选器设置是否正确?

5f0d552i

5f0d552i1#

创建一个过滤器类:

public class CORSFilter implements Filter{

        @Override
        public void init(FilterConfig filterConfig) throws ServletException {

        }

        @Override
        public void doFilter(ServletRequest req, ServletResponse res,
                FilterChain chain) throws IOException, ServletException {

            HttpServletResponse response = (HttpServletResponse) res;
            response.setHeader("Access-Control-Allow-Origin", "*");
            response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT");
            response.setHeader("Access-Control-Max-Age", "3600");
            response.setHeader("Access-Control-Allow-Headers", "x-requested-with,content-type");
            chain.doFilter(req, res);

        }

        @Override
        public void destroy() {

        }

    }

然后将类添加到过滤器列表中

<filter>
    <filter-name>LogFilter</filter-name>
    <filter-class>
        net.viralpatel.servlet.filters.CORSFilter
    </filter-class>
    <init-param>
        <param-name>test-param</param-name>
        <param-value>This parameter is for testing.</param-value>
    </init-param>
</filter>

更多关于主题的文档http://viralpatel.net/blogs/tutorial-java-servlet-filter-example-using-eclipse-apache-tomcat/
希望能有所帮助

6ie5vjzr

6ie5vjzr2#

Tomcat CORS过滤器允许标题参数cors.allowed.headers仅允许以下值X-Client-Context-Id, Origin, Authorization, Accept, Access-Control-Request-Method, Cache-Control, Access-Control-Request-Headers, Accept-Language, Pragma, Content-Language, Content-Type。如果您的预检请求包含除上述标题之外的任何内容,您将返回403未授权错误(可能在过滤器链的深处有其他过滤器生成403,我正在尝试跟踪它)。看起来您有两个自定义头文件if-match,if-non-match可能就是导致问题的原因。

相关问题