SvelteKit:如何保护路由与localStorage?



所以我做了一个+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.

你真的不应该用localStorage

SvelteKit默认使用服务器端渲染,您无法访问服务器上的浏览器存储,但您将获得cookie。

使用浏览器存储时的唯一选择是关闭服务器端呈现。不建议使用

最新更新