0

I am trying to call method of controller from reactJs and both are running on same machine but different port and it shows an error of Cors.

Access to XMLHttpRequest at 'http://localhost:8080/registration' 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.

Here is the code of React side:

 const getHeaders = () => {
        let authToken = localStorage.auth_token ? localStorage.auth_token : null;

    let config = {
        headers: {
            Authorization: authToken,
           'Accept': 'application/json',
        },

    };
    return authToken ? config : {};
};


const axiosPost = async (data, url) => {
    try {
        debugger;
        console.log(data);
        console.log(url);
        return await axios.post(`${BASE_URL}/${url}`, data, getHeaders());
    } catch (error) {
        checkError(error);
        throw error.response.data;
    }
};

This is controller from Java side:

@GetMapping(value = "/registration",produces = "application/json", consumes = "application/json")
public @ResponseBody ModelAndView Home(){
}
Oguz Ozkeroglu
  • 3,025
  • 3
  • 38
  • 64
  • 1
    Does this answer your question? [How to solve 'Redirect has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header'?](https://stackoverflow.com/questions/46522749/how-to-solve-redirect-has-been-blocked-by-cors-policy-no-access-control-allow) – NullPointerException Nov 20 '19 at 21:54

2 Answers2

0

If you can able to change server side, you can use @CrossOrigin(origins = "http://localhost:3000") annotation. For detailed information, check this link out: Controller method CORS configuration

Oguz Ozkeroglu
  • 3,025
  • 3
  • 38
  • 64
0

This is the CORS configuration for my Spring Boot and React application.

It works when pages are served from Spring and also when pages are server from webpack dev-server.

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    private final long MAX_AGE_SECS = 3600;

    @Override
    public void addCorsMappings(CorsRegistry registry) {
    registry.addMapping("/**")
            .allowedOrigins("*")
            .allowedMethods("HEAD", "OPTIONS", "GET", "POST", "PUT", "PATCH", "DELETE")
            .maxAge(MAX_AGE_SECS);
    }
}
jordiburgos
  • 5,964
  • 4
  • 46
  • 80