1
votes

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

3

3 Answers

0
votes

I found out the solution. I fixed it by adding this line to my spring securty web config

protected void configure(HttpSecurity httpSecurity) throws Exception {
        httpSecurity.cors();
//other configs
 }
0
votes

I fixed it by adding this line

httpSecurity.authorizeRequests().antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
-1
votes

I don't know what's in the middle of your controller, but you can try to remove AxiosRequestConfig.

function getData() {
  const baseURL = 'http://localhost:8181';
  axios.get(baseURL).then((result) => {
    console.log(result);
  });
}

If the request type is a POST type

function getData() {
  const baseURL = 'http://localhost:8181';
  axios.post(baseURL).then((result) => {
    console.log(result);
  });
}