【发布时间】:2020-11-08 13:25:01
【问题描述】:
我有一个 CORS 问题,我认为所有设置都已正确配置。请求通过了 OPTIONS 预检没有问题,但 POST 请求缺少 CORS 标头“Access-Control-Allow-Origin”的 CORS 问题。我不知道为什么会发生这种情况,因为其他 GET 请求和 OPTIONS 请求工作正常。该 api 需要 Cookie 和 X-X-XSRF-TOKEN。我可以在 POSTMAN 中访问这些 api 数据。
是因为请求载荷的原因吗?
我的 Chrome 错误:
Access to XMLHttpRequest at 'http://example.com:8080/login' from origin 'http://example.com' has been blocked by CORS policy: The value of the 'Access-Control-Allow-Credentials' header in the response is '' which must be 'true' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.
我已添加:
axios.defaults.withCredentials = true
axios.defaults.crossDomain = true
我的发帖请求:
async submitLogin() {
const headers = { "Content-Type": "multipart/form-data" };
const formData = new FormData();
formData.append("username", "example1");
formData.append("password", "example1");
axios
.post("http://example.com:8080/login", formData, {
headers: headers,
})
.then(function (response) {
console.log(response);
});
},
我的 Tomcat web.xml 配置:
<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>http://example.com</param-value>
</init-param>
<init-param>
<param-name>cors.allowed.methods</param-name>
<param-value>GET,POST,HEAD,DELETE,PUT,OPTIONS</param-value>
</init-param>
<init-param>
<param-name>cors.allowed.headers</param-name>
<param-value>Cache-Control,Accept-Language,Accept-Encoding,x-requested-with, Content-Type, origin, authorization, Accept,Content-Length, Connection,Referer,client-security-token,Access-Control-Allow-Credentials,Cookie,Authorization,Content-Type,X-Requested-With,accept,X-XSRF-TOKEN,Origin,Access-Control-Request-Method,Access-Control-Request-Headers</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>
<init-param>
<param-name>cors.preflight.maxage</param-name>
<param-value>10</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CorsFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
Successfully passed OPTIONS Preflight Request Request Header
【问题讨论】:
-
您请求数据的服务器需要将您列入其白名单。另一种选择是使用代理。除此之外,我不建议您允许所有带有 * 的来源。在生产中,为您的前端设置您的后端作为允许的来源,在开发中使用代理。 developer.mozilla.org/en-US/docs/Web/HTTP/CORS
-
@Deniz 感谢您的回复,我会先尝试在开发中使用代理。我已经设置了 cors.allowed.origins 并且它具有 fontend 域。我不明白为什么它通过了 OPTIONS 预检而不是实际的 POST 请求。