Nodejs 从 POST 方法重定向无效

Nodejs redirect from POST method not working

我有一个注销按钮,它发送一个 POST 请求。之后它应该将用户重定向到主页,但没有任何反应。我还尝试将状态码设置为 302、303...

代码:

//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

如果您的 /logout 端点接受 GET 请求,请尝试将用户重定向到那里。例如:

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

否则,清除 cookie 后,在 JavaScript 中添加重定向:

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