CORS已启用,但请求头来自不同的主机。

7

我有一个启用了CORS的Tomcat 8服务器,配置在web.xml文件中。 CORS插件在大多数情况下都可以正常工作,但有时会混淆本地主机和服务器主机的头部请求。

XMLHttpRequest cannot load http://mipldevlinux7:6060/juneberry/data/blue-marbles/config.json. The 'Access-Control-Allow-Origin' header has a value 'http://localhost:3000' that is not equal to the supplied origin. Origin 'http://mipldevlinux7:7777' is therefore not allowed access

我的Tomcat服务器位于名为mipldevlinux7的服务器上的端口6060,我在同一主机上的端口7777上有一台生产服务器。
我在localhost:3000上进行开发,我的同事在localhost:8080上运行他的开发服务器。
我们遇到了CORS错误,错误混淆了我们的本地主机与30008080之间的标头。有时我们甚至会收到来自mipledevlinux7:7777的标头请求,而我们是从本地主机请求的。
我使用的CORS是内置在Tomcat 8中提供的。
<filter>
  <filter-name>CorsFilter</filter-name>
  <filter-class>org.apache.catalina.filters.CorsFilter</filter-class>
  <init-param>
        <param-name>cors.allowed.origins</param-name>
        <param-value>*</param-value>
    </init-param>
    <init-param>
        <param-name>cors.allowed.methods</param-name>
        <param-value>GET,POST,HEAD,OPTIONS,PUT</param-value>
    </init-param>
    <init-param>
        <param-name>cors.allowed.headers</param-name>
        <param-value>Content-Type,X-Requested-With,accept,Origin,Access-Control-Request-Method,Access-Control-Request-Headers,Last-Modified</param-value>
    </init-param>
    <init-param>
        <param-name>cors.exposed.headers</param-name>
        <param-value>Access-Control-Allow-Origin,Access-Control-Allow-Credentials</param-value>
    </init-param>
    <init-param>
        <param-name>cors.support.credentials</param-name>
        <param-value>true</param-value>
    </init-param>
</filter>
<filter-mapping>
  <filter-name>CorsFilter</filter-name>
  <url-pattern>/*</url-pattern>
</filter-mapping>

Tomcat是否缓存请求头或者使用上一次请求的请求头导致混乱,并阻止了所有请求?


你尝试将 cors.preflight.maxage 设置为 -1 吗?根据文档流程图,如果 cors.support.credentials 为 true,则 Access-Control-Allow-Origin 不会设置为 *,而是设置为 origin header。在你的情况下,这可能是浏览器缓存问题(Tomcat 告诉浏览器缓存预检请求结果1800秒)。 - David Duponchel
1个回答

0

如果您将cors.support.credentials设置为true,则使用cors.preflight.maxage设置为-1以禁用浏览器缓存:

<init-param>
    <param-name>cors.preflight.maxage</param-name>
    <param-value>-1</param-value>
</init-param>

你确定要将cors.allowed.origins设置为*吗?


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接