[nuxt] [请求错误] [未处理] [500] localStorage 未定义 14:42:56 在 isAuthenticated (C:\Users\Lenovo\Desktop\CRM uenuxi\middleware uth.global.js:10:17) 在 C:\Users\Lenovo\Desktop\CRM uenuxi\middleware uth.global.js:28:22 在异步 ViteNodeRunner.directRequest (/C:/Users/Lenovo/Desktop/CRM/vuenuxi/node_modules/vite-node/dist/client.mjs:334:5) 在异步 ViteNodeRunner.cachedRequest (/C:/Users/Lenovo/Desktop/CRM/vuenuxi/node_modules/vite-node/dist/client.mjs:190:14) 在异步 ViteNodeRunner.dependencyRequest (/C:/Users/Lenovo/Desktop/CRM/vuenuxi/node_modules/vite-node/dist/client.mjs:224:12) 在异步 C:\Users\Lenovo\Desktop\CRM uenuxi irtual:nuxt:C:\Users\Lenovo\Desktop\CRM uenuxi.nuxt\middleware.mjs:2:31 在异步 ViteNodeRunner.directRequest (/C:/Users/Lenovo/Desktop/CRM/vuenuxi/node_modules/vite-node/dist/client.mjs:334:5) 在异步 ViteNodeRunner.cachedRequest (/C:/Users/Lenovo/Desktop/CRM/vuenuxi/node_modules/vite-node/dist/client.mjs:190:14) 在异步 ViteNodeRunner.dependencyRequest (/C:/Users/Lenovo/Desktop/CRM/vuenuxi/node_modules/vite-node/dist/client.mjs:224:12) 在异步 C:\Users\Lenovo\Desktop\CRM uenuxi 颂歌模块 uxt\dist\页面 取消时间\插件 外部.js:12:32 [nuxt] [请求错误] [未处理] [500] localStorage 未定义 14:42:56 在 isAuthenticated (C:\Users\Lenovo\Desktop\CRM uenuxi\middleware uth.global.js:10:17)
//auth.global.js
import { defineNuxtRouteMiddleware, navigateTo } from "nuxt/app";
import axios from "axios";
async function isAuthenticated() {
let token = localStorage.getItem("token")
if (!token) {
return false;
}
try {
const res = await axios.get("/user", {
headers: {
Authorization: `Bearer ${token}`,
token: token,
},
});
return res.status === 200;
} catch (err) {
return false;
}
}
const isAuth = await isAuthenticated()
export default defineNuxtRouteMiddleware(async(to, from) => {
const isDashboardRoute = /^\/dashboard/.test(to.fullPath);
if (isDashboardRoute && !isAuth) {
return navigateTo("/auth/login");
}
if (to.fullPath === "/auth/login" && isAuth) {
return navigateTo("/dashboard");
}
if (to.fullPath === "/auth/register" && isAuth) {
return navigateTo("/dashboard");
}
});
nuxt.congig.js
import { defineNuxtConfig } from 'nuxt/config'
export default defineNuxtConfig({
css: ["~/assets/css/tailwind.css", "~/assets/fontawesome/css/all.css"],
postcss: {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
},
modules: [
"@pinia/nuxt",
"@nuxt/devtools",
"nuxt-icon",
],
devtools: {
// Enable devtools (default: true)
enabled: true,
// VS Code Server options
vscode: {},
// ...other options
},
ssr:true,
});
正如@justanotherpeter提到的,您只能在客户端使用localStorage。或者,您可以使用 cookie 进行身份验证。 Nuxt 3 有 useCookie 可组合。
正如@justanotherpeter提到的,你只能在客户端使用localStorage,但如果你不使用SSR功能,你可以禁用它:
// file: nuxt.config.js
export default defineNuxtConfig({
// ...
ssr: false
});
这应该可以解决你的问题