I am having below problem with the fetch function: React code:
componentDidMount() {
this.userService.getLoggedInUser()
.then(user => {
this.setState({user: user});
console.log(this.state.user);
})
}
This the course service file code:
getLoggedInUser(){
const USER_API_URL = API_URL + "/api/profile";
return fetch(USER_API_URL, {
headers : {
'Content-Type' : 'application/json'
},
method : "POST"
}).then(response => response.clone()).then(data => {
console.log(data);
return data;
}).catch(function (err) {
console.log(err)
});
}
I am just trying to get the logged in user from the server. While using postman to do the same, I am getting the output as expected. Server Code:
@PostMapping("/api/loggedInUser")
public Faculty getLoggedInUser(HttpSession session){
return (Faculty)session.getAttribute("currentUser");
}
Class in the server is defined as:
@RestController
@CrossOrigin(origins = "http://localhost:3000", allowCredentials ="true")
public class UserService {
In postman, I am getting the below output:
{
"id": 100,
"username": "bird",
"password": "bird",
"firstName": "Alice",
"lastName": "Kathie"
}
But in the react app, I am getting in the console as:
Response {type: "cors", url: "http://localhost:8080/api/profile", redirected: false, status: 200, ok: true, …}
But there is no data body to return or parse. I am not sure what I am doing wrong here. I have tried changing the then method in the fetch to various types, like response.clone().json() etc, but, in most cases, I am getting the output as "promise rejected, unexpected end of json input". How can I solve this problem? Thanks