【发布时间】: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" 标头。