typescript SvelteKit:如何使用localStorage保护路由?

64jmpszr  于 2023-04-07  发布在  TypeScript
关注(0)|答案(1)|浏览(127)

所以我做了一个+page.ts来保护我的路由,但是get localStorage没有定义?

import type { PageLoad } from "./$types"
import {redirect} from "@sveltejs/kit";
import axios from 'axios';

axios.interceptors.request.use(function (config) {
    let authToken = localStorage.getItem('auth_token');

    if (authToken !== null) {
        config.headers.Authorization = 'Bearer ' + authToken;
    }

    config.headers["Content-Type"] = "application/json";

    return config;
});

export const load: PageLoad = async () => {
    if (localStorage.getItem('auth_token') === null) {
        throw redirect(302, '/')
    }
    axios.get(import.meta.env.VITE_API_URL + '/auth/me')
        .then(function (response) {
        })
        .catch(function (error) {
            localStorage.removeItem('auth_token')
            throw redirect(302, '/')
        });
}

我读到的每一个问题都提到了cookie,当你不使用上述技术时,很难知道该怎么做......我使用的是localStorage。

qvtsj1bj

qvtsj1bj1#

你真的不应该使用localStorage
默认情况下,SvelteKit使用服务器端渲染,您无法访问服务器上的浏览器存储,但您将获得Cookie。
使用浏览器存储时,唯一的选择是关闭服务器端渲染。不推荐这样做。

相关问题