@CrossOrigin not working with POST method

Hello I`m developing a web app. Backend is running with Spring and frontend with React. I have problem with CrossOrigin if I am using POST Http method. Here is my js code:

const LOGIN_URL = "http://localhost:8080/auth/login";

login(username, password) {
return axios.post(LOGIN_URL, {
  username,
  password,
});

}

Here I am getting an error:

  • Origin http://localhost:3000 is not allowed by Access-Control-Allow-Origin.
  • XMLHttpRequest cannot load http://localhost:8080/auth/login due to access control checks.
  • Failed to load resource: Origin http://localhost:3000 is not allowed by Access-Control-Allow-Origin.

Java Spring sample code:

@CrossOrigin(origins = "*")

@RestController
@RequestMapping("/auth")

public class AuthController {

 ...

@PostMapping("/login") 

public ResponseEntity<?> signInUser(@RequestBody LoginBody loginBody){

.....

 return ResponseEntity.ok("OK");

}

But if I use GET request, like this:

JS Code:

  hello() {
return axios.get(HELLO_URL);}

Java Code:

@CrossOrigin
@RestController
@RequestMapping("public")
public class HelloWorld {

@GetMapping("/hello")
public String helloWorld() {return "Hello ";}

}

I dont have errors. Everything works fine

Do you have any idea how fix this issue?

Answer

Add @CrossOrigin on top of your @PostMapping(“/login”) annotaion instead of using at the class level.