I've been working on a project using Traccar API and React.
My problem is that I want to save the value of set-cookie response Header, to store it in the browser's cookies.
I want to do this because, neither Firefox or Chrome set the cookie on the browser.
But on both browsers I get the same response Header.
This is my function, and as you can see, I tried to get the value of set-cookie using response.headers.get()
const login = async () => {
setLoading(true);
const myHeaders = new Headers();
myHeaders.append("Authorization", "Basic Og==");
myHeaders.append("Content-Type", "application/x-www-form-urlencoded");
var urlencoded = new URLSearchParams();
urlencoded.append("email", user.email);
urlencoded.append("password", user.password);
var requestOptions = {
method: 'POST',
headers: myHeaders,
body: urlencoded,
credentials: 'include',
redirect: 'manual',
}
trackPromise(
fetch("http://x.x.x.x:7082/api/session", requestOptions)
.then((response) => {
if (response.ok) {
console.log('Cookie: '+response.headers.get('set-cookie'))
redirect();
} else {
alert('There was a problem');
}
})
.catch(error => console.log('error', error))
);
}
But everytime I call the request, the result is the same.
Also, i tried to modify the credentials
Header and using credentials: include
,credentials: same-origin
and credentials: omit
, but still no luck.
I've been stuck with this problem for over a week, One of the things that I have noticed is that when testing the API methods in Postman, the JSESSIONID value, which come from set-cookie, is always used, this value is returned as a Response Header, but in the Code Snippets, is also set as a Request Header, that makes sense because every method on the API using Postman uses it as a Request Header.
So, how to get this value?
Something similar fetch: Getting cookies from fetch response
Check what headers you can read:
If cookies was already set, try to access them as
document.cookies
. (it won'r work for cookies that flagged as httpOnly)