英文:
Cannot access localstorage from sveltekit hook
问题
以下是代码的翻译部分,不包括问题和回答:
我有一个用来验证用户是否已登录的函数:
export const isUserLoggedIn = () => {
let dmcAuthToken = localStorage.getItem(AUTH_TOKEN_KEY);
return dmcAuthToken ? true : false;
}
当用户登录时,本地存储会被更新,其中包含从后端返回的令牌:
localStorage.setItem(AUTH_TOKEN_KEY, dmcAuthToken);
现在,我正在尝试在用户未登录时限制访问页面。我阅读了一些内容,发现了一个名为handle
的钩子,所以我决定在那里实现这个逻辑:
/src/hooks.js
:
export async function handle({ event, resolve }) {
if (!isUserLoggedIn() && event.url.pathname != "/login") {
console.log("用户未登录");
return new Response(null, {
status: 302,
headers: {
location: "/login"
}
})
}
if (isUserLoggedIn() && event.url.pathname == "/login") {
return new Response(null, {
status: 302,
headers: {
location: "/pos"
}
})
}
return resolve(event);
}
但是我遇到了一个错误:
500 localStorage 未定义
你知道发生了什么吗?
在测试时,如果我从isUserLoggedIn
返回true
或false
,钩子中实现的逻辑似乎有效,但问题出在尝试访问localStorage
时。为什么会这样呢?
我看到有一种解决方案是将令牌保存在存储中,但除非必要,我不想采用这种方法。我想知道为什么我的方法不起作用。
谢谢。
英文:
I've got a function that verifies whether an user is logged in or not:
export const isUserLoggedIn = () => {
let dmcAuthToken = localStorage.getItem(AUTH_TOKEN_KEY);
return dmcAuthToken ? true : false;
}
when an user logs in, local storage is updated with a token returned from the backend:
localStorage.setItem(AUTH_TOKEN_KEY, dmcAuthToken);
Now, I'm trying to restrict access to pages when the user is not logged, I've read a bit and found a hook called handle
so I decided to implement this logic there:
/src/hooks.js
:
export async function handle({ event, resolve }) {
if (!isUserLoggedIn() && event.url.pathname != "/login") {
console.log("user NOT logged in");
return new Response(null, {
status: 302,
headers: {
location: "/login"
}
})
}
if (isUserLoggedIn() && event.url.pathname == "/login") {
return new Response(null, {
status: 302,
headers: {
location: "/pos"
}
})
}
return resolve(event);
}
But I'm getting an error:
500 localStorage is not defined
any idea what's going on?
For testing, if I return either true
or false
from isUserLoggedIn
the implemented logic in the hook seems to work, but the issue is when trying to access localStorage
, why is that?
I've seen solution where the token is saved in a store but don't wanna go that route unless it's necessary, I'd like to know why my way isn't working.
Thanks
答案1
得分: 1
这是因为localStorage
在服务器端不可用,请使用cookie
来保存令牌。
英文:
that's because localStorage
is not available on the server side
please use cookie
to save token
答案2
得分: 0
因为 hook 在服务器端运行,所以可能会出现这个问题。尝试添加 !browser
进行检查,或者使用 typeof window !== 'undefined'
。
英文:
Probably because hook runs on server side. Try adding !browser
to check. Or typeof window !== 'undefined'
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论