Languages

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

1 points
Asked by:
Marcin
16180

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();
    console.log(users);
}
let users = getUsers();

How to fix this problem?

1 answer
4 points
Answered by:
Marcin
16180

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
@RestController
@RequestMapping("/users")
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 - friendly IT community for everyone.

ÔŁĄ´ŞĆ­čĺ╗ ­čÖé

Join