CORS headache in ReactJS and Spring boot

Job Kilonzo
2 min readApr 17, 2021

Have you ever written a ReactJS app? Okay, if you have, fine. Have you ever called an API using ReactJS? Be it a NodeJS API, spring boot API, PHP API, or just data you crawled from a website of your choice. If yes, then I know you have met the below error

Before we continue let’s understand what is CORS. Cross-origin resource sharing (CORS) is a mechanism that allows restricted resources on a web page to be requested from another domain outside the domain from which the first resource was served

The above error took me few hours while searching for its solution. All solutions in stack overflow were not working for me. Then remembered I didn’t go through the spring documentation to check whether I can get a solution from there(My bad).

To solve the above error in spring boot and ReactJS you only need to add one line, @CrossOrigin in the controller. This adds the CORS access control header in its response to avoid been blocked by CORS.

This is the result without adding CORS access control header.

After adding the CORS access control header.

Boom! Solved.

Learn more, https://spring.io/guides/gs/rest-service-cors/

Thank you for reading.

--

--

Job Kilonzo

I'm Software Engineer as well as accountant interested in contributing to the technology and accounting profession.