CORS error when connecting local React frontend to local Spring Boot middleware application CORS error when connecting local React frontend to local Spring Boot middleware application reactjs reactjs

CORS error when connecting local React frontend to local Spring Boot middleware application


I also had this issue, but allow me to give a straight forward answer in a simpler communication manner.

First and foremost, you have to tell your server (Spring boot java), about the client (Reactjs ) URL.

For example, most of the times spring boot uses http://localhost:8080 and Reactjs uses http://localhost:3000.

So you have to navigate to the controller in Spring boot java and allow the URL of Reactjs to be given the permission for accessibility in the server (Spring boot). This will help you get rid of the CORS issue.

How do we do this in Spring boot? simply we add the @CrossOrigin annotation specifying the Reactjs URL link as below:

For example :

    @GetMapping("/orphans")    @CrossOrigin(origins = "http://localhost:3000")    Iterable<Student> read() {        return studentService.findAll();    }

The method above is to list all the orphans, so I gave Reactjs URL link permission then I got rid of the CORS issue.

Happy coding.


Controller.java

Refer to the below sample code to resolve this issue.

@CrossOrigin(origins = "http://localhost:3000")@RequestMapping(value="/sample", method = RequestMethod.GET, produces = "application/json")public Student getStudent(){}


This is a standard CORS issue, this basically means that user agent i.e. http://localhost:3000 doesn't have permissions to access resources at http://localhost:8085. You can learn more about it at https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS.

Your request headers should exactly map to server rules. Keeping any parameter as * won't work.

For e.g., if your request header has following:

Access-Control-Request-Method: POSTAccess-Control-Request-Headers: <your custom headers>

Then, server rules show map your request header:

Access-Control-Request-Method: GET, PUT, DELETE, POSTAccess-Control-Request-Headers: <your custom headers>

Let me know if it helps!