I have a Node app with this simplified API that checks if user is authenticated (with session):
export default (req, res,) => {
if (!req.session || !req.session.loggedIn) {
return res.status(401).send();
}
return res.status(200).send();
};
In Postman everything works well, but when React client makes this request:
axios.get(`${domain}/is-auth`)
.then((res) => {
return res.status === 200;
})
.catch((err) => {
throw err;
});
... it always gets 401 and return false. The server can't see its session. I am reading it's about cookies but aren't cookies supposed to be kept and sent by browser automatically? If not then how I can do that? Please help.
fetch
and axios
indeed do not send credentials automatically with the request, you will have to specify it by setting the "withCredentials" option to true:
axios.get(`${domain}/is-auth`, { withCredentials: true })
.then((res) => {
return res.status === 200;
})
.catch((err) => {
throw err;
});