弹簧 cors 在获取时被阻塞
Posted
技术标签:
【中文标题】弹簧 cors 在获取时被阻塞【英文标题】:spring cors blocked on get 【发布时间】:2020-04-20 11:51:24 【问题描述】:在我的 spring 服务器中,我添加了这个来启用 cors:
@Bean
public WebMvcConfigurer corsConfigurer()
return new WebMvcConfigurer()
@Override
public void addCorsMappings(CorsRegistry registry)
registry.addMapping("/*").allowedOrigins("http://localhost:3000");
;
在我的 react.js 客户端中,当我 POST 时我没有收到任何错误,但是当我尝试 GET 时,我收到错误消息:
从源“http://localhost:3000”访问“http://localhost:8080/user/aweq”处的 XMLHttpRequest 已被 CORS 策略阻止:请求的资源上不存在“Access-Control-Allow-Origin”标头。
代码:
let url=constant.serverURL+"user/"+this.state.username;
axios.get(url).then((res)=>console.log(res));
我什至试过这个:
let url=constant.serverURL+"user/"+this.state.username;
axios.get(url,
headers:
"Content-Type": "application/json"
).then((res)=>console.log(res));
【问题讨论】:
从 axios.get 请求中移除整个 headers 块。 GET 请求中没有请求正文,因此无需为请求设置 "Content-Type": "application/json" 标头。 【参考方案1】:在您的全局配置中,您提供了错误的映射,为了在所有端点上启用 cors,您需要将映射提供为 /**
:
@Bean
public WebMvcConfigurer corsConfigurer()
return new WebMvcConfigurer()
@Override
public void addCorsMappings(CorsRegistry registry)
registry.addMapping("/**").allowedOrigins("http://localhost:3000");
;
官方doc
【讨论】:
【参考方案2】:我认为唯一应该解决的是
registry.addMapping("/**").allowedOrigins("http://localhost:3000");
so from /* => /**, 覆盖路径 /user/username
在此处查找路径中的通配符 https://help.sumologic.com/03Send-Data/Sources/04Reference-Information-for-Sources/Using-Wildcards-in-Paths
【讨论】:
以上是关于弹簧 cors 在获取时被阻塞的主要内容,如果未能解决你的问题,请参考以下文章