DEV Community

Ninan Kara
Ninan Kara

Posted on

1 1

Day 5: CORS Setting for REST API in ReactJS

Intro

Please note that this solution is only applied for REST API that is developed using Spring framework, such as Spring Boot.

Dev Environment

  • React JS
  • Spring Boot
  • Axios
  • Heroku

Problem

Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource
Enter fullscreen mode Exit fullscreen mode

I have problem when calling REST API, deployed in Heroku, from localhost of my ReactJS web application.

Solution

Simply add annotation in the controller backend. Please refer to reference below.

@CrossOrigin(origins = "http://localhost:3000/", maxAge = 3600)
@RestController

.....

Enter fullscreen mode Exit fullscreen mode

Actually I took the wrong approaches when looking for solution. If you simply copy paste the error from browser, the result will bring you to another solution. Some said to add certain value in header of the request data, some said to create cors proxy, etc.

That is not wrong, but not applicable for my problem. Honestly I've tried everything I found, but nothing works. Then suddenly I got a light bulb. The other solution said that other than client side, if you developed your REST API, then it is more simpler to add the cors setting from backend side. Then I searched the solution for Spring Boot :)

Its another story if we consume the available api. Then it might be more complicated.

References

Tutorial

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

While many AI coding tools operate as simple command-response systems, Qodo Gen 1.0 represents the next generation: autonomous, multi-step problem-solving agents that work alongside you.

Read full post

Top comments (0)

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post