spring - Axios CORS 错误(403)甚至服务器允许所有
问题描述
我尝试使用 Axios POST 请求从 Springboot 服务器获取 jwt 令牌,但出现以下错误:
xhr.js:166 OPTIONS url net::ERR_ABORTED 403
Access to XMLHttpRequest at 'url' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
似乎它无法通过带有“Access-Control-Allow-Origin”标头的预检请求。所以我在标题上配置了“Access-Control-Allow-Origin”,但不知何故它仍然无法正常工作。
这是代码:
反应:
return Axios({
method: 'post',
url: 'url',
data: qs.stringify(json),
headers: {
'content-type': 'application/x-www-form-urlencoded;charset=UTF-8',
'authorization': 'Basic token',
},
});
弹簧靴:
@Bean
CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration conf = new CorsConfiguration();
conf.setAllowedOrigins(Arrays.asList("*"));
conf.setAllowedMethods(Arrays.asList("POST", "GET", "OPTIONS", "DELETE", "PUT"));
conf.setAllowedHeaders(Arrays.asList("Content-Type", "X-Requested-With", "accept,Origin", "Access-Control-Request-Method", "Access-Control-Request-Headers", "Authorization", "Cache-Control", "Access-Control-Allow-Origin"));
conf.setAllowCredentials(true);
conf.setMaxAge(3600L);
...
}
解决方案
试试这个,默认情况下允许所有标题和 URL 只是为了检查
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedOrigins("*")
.allowedMethods("GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS").allowedHeaders("*")
.allowCredentials(true).maxAge(MAX_AGE_SECS);
}
你的网址也不应该没有引号
return Axios({
method: 'post',
url: url, // like this
data: qs.stringify(json),
headers: {
'content-type': 'application/x-www-form-urlencoded;charset=UTF-8',
'authorization': 'Basic token',
},
});
最后只是做个笔记
检查您的 URL 是否在安全配置中被允许,否则您将得到 403
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
...
.antMatchers("/url*").permitAll() // Allow whatever url is passed
...
;
}
推荐阅读
- go - 如何在 https 中以生产模式运行 Beego 二进制文件?
- r - 如何绘制按月分组的每小时平均时间序列?
- robotframework - “应该是真的 ${list} == ['a', 'b', 'c']” 和 “应该是真的 $list == ['a', 'b', 'c' 有什么区别? ]”?
- javascript - 在提交时保持价值
- applescript - 如何在 Apple Mail Rule 上触发 AppleScript?
- sql-server - SQL Server GROUP BY 但需要一个详细信息列
- php - 每个 TCP 连接上的误报 SYN 泛洪检测
- c# - 为什么 JsonSerializer 给空?
- node.js - FFMPEG 和 Node.js Spawn 不输出任何内容
- r - 在 R data.frame 中查找常量列的名称