送了一个幽灵 GET 请求"/>
本地重定向出于某种原因发送了一个幽灵 GET 请求
我正在尝试创建具有以下行为的网站:
- 如果用户试图在未经身份验证的情况下访问 /home 页面,他将被重定向到 /login 页面。
- 一旦他通过 /login 页面登录,他就会收到一个会话 cookie 并被重定向到 /home 页面
- 如果用户返回 /login 页面但有一个有效的会话 cookie,他会自动重定向到 /home 页面
我在 express 中使用 node.js。 这是我使用的当前代码: 服务器端:
app.get('/login', (req, res) => {
res.sendFile(__dirname + "/html/login.html")
});
app.post('/login', (req, res) => {
//try to authenticate the user
//if invalid user_id or password
res.status(401).end();
//else creating a cookie and registering the session
res.cookie("session_token", sessionToken, { sameSite: 'Strict', expires: expiresAt })
res.cookie("session_id", id, { sameSite: 'Strict', expires: expiresAt })
res.status(200).send()
});
app.get('/home', (req, res) => {
//if the user can't be authenticated
if (!function_to_authenticate_the_user(req)) return res.redirect(308,'/login')
//else
res.status(200).sendFile(__dirname + "/html/home.html")
});
app.get('/isSessionValid', loginRL, (req, res) => {
if (function_to_authenticate_the_user(req)) return res.status(200).send();
else return res.status(401).send()
});
用户端(功能由按钮上的 onclick 属性触发):
function login(id, mdp) {
fetch('/login', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
'id': id,
'password': password
})
}).then(res => {
if (res.status === 401) {
// display error message
} else if (res.status === 200) {
location.replace('/home')
}
})
}
window.addEventListener('load', () => {
if (!document.cookie) return
const cookies = Object.fromEntries(document.cookie.split('; ').map(c => c.split('=')));
if (!cookies.session_token || !cookies.session_id) return
fetch('/isSessionValid', {
method: 'GET',
}).then(res => {
if (res.status === 200) location.replace('/home')
})
});
问题:
出于某种我不明白的原因,一旦用户向 /login 发送 POST 请求并获得带有 cookie 的 200 响应,它就会向 /home 页面发送 GET 请求(这是它应该做的)但还有另一个GET 请求到 /login 页面(我不明白为什么)
它同时发送两个请求。并且出于某种原因,(第二个)/login 请求被优先考虑并且浏览器自动将 GET /home 解释为 308 状态(服务器从不接收任何对 /home 的请求)
由于用户现在有一个有效的会话 cookie,浏览器会再次尝试重定向到 /home,但也会自动向 /login 发送另一个 GET 请求,并一遍又一遍。
我尝试同时调试服务器端和用户端。 出于某种原因,服务器似乎永远不会从 /home 收到任何 GET 请求 我试图删除窗口加载事件侦听器,但它仍然向 /login 发送另一个获取请求,并且从未成功重定向到 /home(它只是停止了永无止境的请求循环)
当我从当前 /login 页面手动将 url 设置为 /home 时,会发生相同的行为(对 /login 的幽灵请求并且不会加载 /home) 我试图将服务器代码更改为:
app.get('/home', (req, res) => {
console.log('received a request')
if (!function_to_authenticate_the_user(req)) {
console.log('trying to redirect')
return res.redirect(301,'/login')
}
res.status(200).sendFile(__dirname + "/html/home.html")
});
但是浏览器一直在控制台中显示以下请求:
GET http://localhost:8000/home [HTTP/1.1 308 Permanent Redirect 0ms]
GET http://localhost:8000/login [HTTP/1.1 200 OK 0ms]
并且服务器从不记录任何内容。
我试图删除用户端代码中的 location.replace('/home') 但它并没有解决问题。
我错过了什么?
回答如下:更多推荐
本地重定向出于某种原因发送了一个幽灵 GET 请求
发布评论