React + Spring Controller - CORS policy: No 'Access-Control-Allow-Origin' header is present

1 points
Asked by:

I write an app with React + Java Spring and encountered problem with ajax request to spring controller.

Error from browser console:

Access to fetch at 'http://localhost:8080/users/getUsers' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

React ajax request:

async function getUsers() {
    const response = await fetch('http://localhost:8080/users/getUsers');
    const users = await response.json();
let users = getUsers();

How to fix this problem?

1 answer
4 points
Answered by:

Add @CrossOrigin annotation to your controller to let the sever accept requests from different domains, in our case localhost:3000.

Working spring controller with @CrossOrigin annotation.

import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestMapping;

@CrossOrigin // <----------------------------- add this
public class UsersController {
    // ...


0 comments Add comment
Native Advertising
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂