【发布时间】:2020-11-12 12:57:25
【问题描述】:
我正在尝试使用 axios 从 api Spring Boot 获取数据。
如果我用 Insomnia 或 Postman 调用 api 它按预期工作,我有如下数据:
[
{
"id": 2,
"username": "Admin",
"profil": null,
"enabled": true,
"roles": [
{
"id": 1,
"name": "Admin"
}
]
}
]
但是使用 axios 或者 fetch 会抛出 Cors 错误:Access to XMLHttpRequest at 'http://localhost:8181' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
所以我很困惑,为什么使用 axios 时没有将标头数据传递给服务器?我不能拥有Authorization 或test
后端配置:
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedOrigins("*");
}
};
}
axios 请求:
function getData() {
const baseURL = 'http://localhost:8181';
const config: AxiosRequestConfig = {
headers: {
Authorization: 'Bearer TQyMDQ1OX0.C5oj83xiEAnRVdXZ24hpZnoRjCA8QsiN23kxylQCwdWCyTJyZOKcH_b4E5Ktv3A0ACVs4mj1XhrmqMJT_MHkeQ',
test: 'test-data',
'Access-Control-Allow-Origin': '*',
},
};
axios.get(baseURL, config).then((result) => {
console.log(result);
});
}
我想我错过了什么。 请帮忙
【问题讨论】:
标签: javascript java reactjs spring-boot axios