I'm trying to fetch data from api Spring Boot using axios.
If I call the api with Insomnia
or Postman
It work as expected, I have the data like:
[
{
"id": 2,
"username": "Admin",
"profil": null,
"enabled": true,
"roles": [
{
"id": 1,
"name": "Admin"
}
]
}
]
But using axios or fetch It throws a Cors error: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
.
So I'm confused, why the header data is not passed to server when using axios ? I can't have the Authorization
or test
BackEnd config:
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedOrigins("*");
}
};
}
Axios request:
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);
});
}
I think I missed something. Need a help please