const express = require('express');
const auth = express.Router();
auth.get('/login', async (req, res) => {
res.render('login')
})
auth.get('/register', async (req, res) => {
res.render('register')
})
auth.post('/logout', async (req, res) => {
res.clearCookie("token")
res.redirect("/auth/login")
});
module.exports = auth
向注销端点发送请求将导致名为 token 的 cookie 被删除。 。对 /logout api 的 post 请求的响应具有指向 auth/login 的位置标头。在网络选项卡中,我也可以看到对 auth/login 的 get 请求的状态代码 200。页面的源代码将更改为 auth/login html 内容,但新页面不会呈现。 登录端点呈现一个login.ejs 文件。
这也是注销按钮事件监听函数:
async function logout() {
fetch('/auth/logout', {
method: 'POST',
credentials: 'include' // This will include the cookie in the request
})
.then(response => {
console.log(`Response status: ${response.status} ${response.statusText}`);
if (response.ok) {
console.log("everything was ok")
} else {
console.error('Logout failed');
}
})
.catch(error => console.error('Error:', error));
}
删除了缓存,没有变化。在 chrome 和 firefox 上也有同样的结论。过程中没有发生错误。
Fetch 返回一个承诺,一旦响应可用,该承诺就会履行,因此它不会像您假设常规表单提交的工作方式一样操作(重定向浏览器)。
当您使用express返回
res.redirect
时,您的前端JavaScript不知道您想要更改浏览器中的页面。 Fetch 将透明地遵循重定向,并再次调用您在 res.redirect
中指定的 url,但如果该 url 返回 HTML,那么它不会突然在您的浏览器中呈现。
幸运的是,从获取请求返回的 Promise 解析为同时具有
redirected
和 url
属性的 Response 对象。
您可以检查
redirected
属性是否为 true
,如果是,请使用 url
属性将浏览器重定向到您的预期目的地。
下面我在您的 fetch 中添加了一个非常简单的示例来重定向,但请阅读有关 fetch 和 Fetch API 的更多信息,以真正了解发生了什么:
fetch('/auth/logout', {
method: 'POST',
credentials: 'include', // This will include the cookie in the request
}).then(response => {
console.log(`Response status: ${response.status} ${response.statusText}`);
if (response.ok) {
console.log("everything was ok")
if(response.redirected){ //< Add this
location.assign(response.url); //< Add this
}
} else {
console.error('Logout failed');
}
}).catch(error => console.error('Error:', error));