英文:
Redirect as a result of an fetch operation
问题
我正在使用纯粹的JavaScript构建一个简单的网站,仅使用fetch API。它与运行Node.js和Express.js的后端通信。当用户登录时,它会获取一个会话cookie。
我的问题是,如果会话无效,我希望重定向到登录页面,对于客户端的任何可能请求。我尝试了从服务器端重定向到登录页面:
res.status(301).redirect("/login.html");
我可以在Web浏览器的开发工具网络选项卡中看到重定向,并且我可以看到它正在执行,并下载login.html文件。但它似乎没有实际导航到页面。我是否漏掉了什么?
有没有更好的方法来解决这个问题?当然,我可以在每次发出请求时在前端进行额外的检查,然后从那里进行重定向,但如果可能的话,我想避免这样做,因为这将产生大量额外的代码。
英文:
I am building a simple website in clean JavaScript, using only fetch API.
It communicates with a backend running Node.js and Express.js.
When the user is logged in, it gets a session cookie.
My problem is that I want an redirect to a login page if the session is not valid, for any of the possible requests by the client.
I've tried from the server side to redirect to the login page:
res.status(301).redirect("/login.html");
I can see the redirect in the developer tools network tab of the web browser, and I can see that it follows it, and downloads the login.html file. But it doesn't seem to actually navigate to the page. Is it something I am missing here?
Is there a better approach to this problem? Of course I could do an extra check in the frontend every time I do a request, and then redirect it from there, but I want to avoid it if possible, as it will produce much extra code...
答案1
得分: 2
如果您尝试显示login.html
而不仅仅是下载它,您可以在调用fetch后检查响应是否被重定向,并将window.location.href
设置为response.url
,如下所示:
fetch(*fetch配置*).then(res => {
// 检查响应是否被重定向,然后更改当前URL
if (res.redirected) window.location.href = res.url;
})
英文:
If you're trying to display login.html
instead of just downloading it, you can check if the response was redirected after calling fetch, and setting window.location.href
to response.url
like so:
fetch(*fetch config*).then(res => {
// Check if the response was redirected and then change the current URL
if (res.redirected) window.location.href = res.url;
})
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论