skip to Main Content

I am trying to call this API from my React.js front end using jwt authentication

const getCategory = () => {
    const token = localStorage.getItem("user");

    return axios
      .get("http://localhost:8080/api/v1/category", {
        withCredentials: true,
        headers: {
          Authorization: `Bearer ${token}`,
        },
      })
      .then((res) => res.json())
      .then((data) => setCategory(data))
      .catch(function (error) {
        console.log(error);
      });
  };

but I always get this error in the console errors:
Access to XMLHttpRequest at ‘http://localhost:8080/api/v1/category’ from origin ‘http://localhost:3000’ has been blocked by CORS policy: Response to preflight request doesn’t pass access control check: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.

and also this:
xhr.js:258 GET http://localhost:8080/api/v1/category net::ERR_FAILED
two times

When I try the same thing from Postman it is working fine. Also I should specify that before that I am hitting this POST request that is used to generate the authentication token:

const login = (email, password) => {
  return axios
    .post(API_URL, {
      email,
      password,
      headers: {
        "content-type": "application/json",
      },
    })

    .then((response) => {
      localStorage.setItem("user", response.data.token);
      return response.data;
    });
};

which is working just fine and I don’t get a cors configuration error

My CORS filter in the Spring Back end looks like this:

@Configuration
@EnableWebMvc
public class CorsConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry){
        registry.addMapping("/api/v1/**")
                .allowedOrigins("http://localhost:3000/")
                .allowedMethods("GET","POST","PUT","DELETE","OPTIONS")
                .allowedHeaders("Authorization","*")
                .exposedHeaders("Authorization")
                .allowCredentials(true)
                .maxAge(3600);
    }
}

I have added it as a class in my project directory. I also have tried to add this in my main application file:

@Bean
    CorsConfigurationSource corsConfigurationSource() {
        final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        final CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        config.addAllowedOrigin("http://localhost:3000/");
        config.addAllowedHeader("*");
        config.addExposedHeader("Authorization");
        config.addAllowedMethod("OPTIONS");
        config.addAllowedMethod("HEAD");
        config.addAllowedMethod("GET");
        config.addAllowedMethod("PUT");
        config.addAllowedMethod("POST");
        config.addAllowedMethod("DELETE");
        config.addAllowedMethod("PATCH");
        source.registerCorsConfiguration("/**", config);
        return source;
    }

2

Answers


  1. Can you try out if you remove the last / from the pattern?

    .allowedOrigins("http://localhost:3000")
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search