React + Spring Controller - CORS policy: No 'Access-Control-Allow-Origin' header is present
I write an app with React + Java (Spring Framework) and encountered problem with AJAX request to Spring Controller.
Error from browser console:
Access to fetch at
'http://localhost:8080/users/get-users'
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:
xxxxxxxxxx
async function getUsers() {
const response = await fetch('http://localhost:8080/users/get-users');
return await response.json();
}
let users = async getUsers();
How to fix this problem?
It looks like you try to do cross origin request that is not permitted by default in modern web browsers.
You need to add @CrossOrigin
annotation to your controller to let the sever accept requests from different origins, in your case localhost:3000
.
Check this:
xxxxxxxxxx
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestMapping;
// <----------------------------- add this
"/users") (
public class UsersController {
// ...
}