Nodejs redirect from POST method not working

Issue

I have a logout button, which sends a POST request. After that it should redirect the user to the main page, but nothing happens. I also tried to set the status code to 302, 303…

Code:

//on click this is executed
function logout() {
  fetch('/logout', { method: 'POST' });
}
//this is called on POST request
const logout = (_req, res) => {
  res.clearCookie('token');
  res.locals.payload = undefined;
  res.redirect('/');                    //problem
};
//logged requests
POST /logout 302 23 - 0.865 ms
GET / 304 - - 6.058 ms

Solution

If your /logout endpoint accepts GET requests, try redirecting the user there instead. For example:

function logout() {
    document.location = '/logout';
}

Otherwise, add a redirect in JavaScript once the cookies are cleared:

async function logout() {
  await fetch('/logout', { method: 'POST' });
  document.location = '/';
}

Answered By – BrownieInMotion

Answer Checked By – Clifford M. (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.