I have a spring boot backend that allows a user to login.
When I use postman to send a json payload to login in a user it returns the correct response with a cookie for a JSESSION.
Postman details with response and cookie
When I send the payload in react (axios) I don't see the cookie for the JSESSION anywhere but the response is still okay ?
const API_URL = "http://localhost:8080/api/auth/";
login(uniqueId: string, password: string) {
return axios.post(API_URL "login", JSON.stringify({
"uniqueId": uniqueId,
"password": password
}),
{
headers: {
'Content-Type': 'application/json',
'withCredentials': 'true'
}
})
.then(response => {
console.log(response);
return response;
}).catch(error => {
return error.response
});
}
Chrome tab with response and no cookie
CodePudding user response:
'withCredentials': 'true'
shoud be outside of headers
(Request Config documentstion)
In your case it would be:
const API_URL = "http://localhost:8080/api/auth/";
login(uniqueId: string, password: string) {
return axios.post(API_URL "login", JSON.stringify({
"uniqueId": uniqueId,
"password": password
}),
{
withCredentials: true,
headers: {
'Content-Type': 'application/json'
}
})
.then(response => {
console.log(response);
return response;
}).catch(error => {
return error.response
});
}
another solution is create instance axios with parametr withCredentials: true
(creating axios instance).
const BASE_URL = "http://localhost:8080/api/";
const api = axios.create({
baseURL: BASE_URL,
withCredentials: true,
headers: {'Content-Type': 'application/json'}
});
and then you can do:
return api.post("/auth/login", JSON.stringify({
"uniqueId": uniqueId,
"password": password
})) .then(response => {
console.log(response);
return response;
}).catch(error => {
return error.response
});