我不是服务器端逻辑的开发人员,但我尝试在前端应用程序上使用 Axios 与其进行交互。
我可以访问代码及其 SpringBoot 应用程序,我注意到 Cors 已启用:
@Override
protected void configure(final HttpSecurity http) throws Exception {
http.cors() ...
}
...
@Bean
CorsConfigurationSource corsConfigurationSource() {
final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", new CorsConfiguration().applyPermitDefaultValues());
return source;
}
我还尝试自己设置 header 值而不调用applyPermitDefaultValues
。我可以在状态代码 200 OPTIONS
请求的 Chrome 浏览器网络选项卡中看到它们,但控制台仍然显示:
Access to XMLHttpRequest at 'http://localhost:8080/login' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.
这是预检响应:
Access-Control-Allow-Headers: authorization, content-type
Access-Control-Allow-Methods: GET,HEAD,POST,OPTIONS,DELETE,PUT
Access-Control-Allow-Origin: *
Access-Control-Max-Age: 1800
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Content-Length: 0
Date: Thu, 16 Jan 2020 17:18:25 GMT
Expires: 0
Pragma: no-cache
Vary: Origin
Vary: Access-Control-Request-Method
Vary: Access-Control-Request-Headers
X-Content-Type-Options: nosniff
X-Frame-Options: DENY
X-XSS-Protection: 1; mode=block
提出请求:
首先创建一个axios实例:
Axios.create({
baseURL:
process.env.NODE_ENV !== "development"
? "..."
: "...",
withCredentials: true,
headers: {
// Auth token
Authorization
}
})
然后我重用此实例并调用 this.api.post(...)
或任何其他方法。
即使返回通配符,所有这些都失败了,我不知道从哪里开始。
为什么我仍然收到 cors 错误。
我该如何解决这个问题?
最佳答案
从此:
从源“http://localhost:3000”访问“http://localhost:8080/login”处的 XMLHttpRequest 已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:当请求的凭据模式为“include”时,响应中“Access-Control-Allow-Origin” header 的值不能是通配符“*”。 XMLHttpRequest发起的请求的凭证模式由withCredentials属性控制。
我认为您的麻烦根源在于请求的 withCredentials
属性设置为 true,在这种情况下 Access-Control-Allow-Origin: *
不能使用,即使没有 Access-Control-Allow-Credentials header 。
有关 withCredentials
参数和响应 header 的更多信息,请参阅本文:https://www.ozkary.com/2015/12/api-oauth-token-access-control-allow-credentials.html
关于javascript - 即使预检响应成功,访问仍被 CORS 策略阻止 存在 'Access-Control-Allow-Origin' 通配符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59774979/