Issue
My spring boot code is
@GetMapping("/currentUser")
public Map<String, String> testController(Authentication authentication){
User user=(User)authentication.getPrincipal();
HashMap<String, String> map = new HashMap<>();
map.put("Role",user.getUserRole().toString());
map.put("Lname",user.getLastName());
map.put("Fname", user.getFirstName());
return map;
}
ReactJS code is
useEffect(() => {
axios.get('currentUser',{headers: {'Content-Type': 'application/json'} },{withCredentials: true},{ crossDomain: true })
.then(response =>{
console.log(response);})
.catch(error => {
console.log(error);
});},[]);
my login and signup (post requests) work but this returns the following error
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8080/currentUser. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8080/currentUser. (Reason: CORS request did not succeed).
Solution
From my experience I suggest you to check the following:
- Do you have the following Annotation at your controller class? It is not shown in your example.
@CrossOrigin("*")
But keep in mind that "*" will allow all origin to access the page. If suggest to restrict this value for production.
- Check your browser network tab in the development tools. This issue can be caused if the request results in a 404 (not found), too. Therefore the CORS message isn´t the cause of your problem.
Answered By - O. Schnieders