无法从 SvelteKit 钩子中访问本地存储。

huangapple go评论67阅读模式
英文:

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返回truefalse,钩子中实现的逻辑似乎有效,但问题出在尝试访问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'

huangapple
  • 本文由 发表于 2023年3月1日 10:09:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/75598963.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定