Javascript 飞行前请求不';无法通过访问控制检查:它没有HTTP ok状态
我正在尝试使用axios从api Spring Boot获取数据 如果我使用Javascript 飞行前请求不';无法通过访问控制检查:它没有HTTP ok状态,javascript,java,reactjs,spring-boot,axios,Javascript,Java,Reactjs,Spring Boot,Axios,我正在尝试使用axios从api Spring Boot获取数据 如果我使用失眠或邮递员调用api,它会按预期工作,我有如下数据: [ { "id": 2, "username": "Admin", "profil": null, "enabled": true, "roles": [ { "
失眠
或邮递员
调用api,它会按预期工作,我有如下数据:
[
{
"id": 2,
"username": "Admin",
"profil": null,
"enabled": true,
"roles": [
{
"id": 1,
"name": "Admin"
}
]
}
]
但是使用axios或fetch会引发Cors错误:访问位于的XMLHttpRequest'http://localhost:8181“起源”http://localhost:3000'已被CORS策略阻止:对飞行前请求的响应未通过访问控制检查:它没有HTTP ok状态
所以我很困惑,为什么在使用axios时头数据没有传递到服务器?我不能进行授权
或测试
后端配置:
@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);
});
}
我想我错过了什么。
需要帮助,请 < P>我不知道你的控制器中间是什么,但是你可以尝试删除AXOSReopestConfig.
function getData() {
const baseURL = 'http://localhost:8181';
axios.get(baseURL).then((result) => {
console.log(result);
});
}
如果请求类型是POST类型
function getData() {
const baseURL = 'http://localhost:8181';
axios.post(baseURL).then((result) => {
console.log(result);
});
}
我找到了解决办法。我通过将这一行添加到我的spring安全web配置中修复了它
protected void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity.cors();
//other configs
}