首页 > 解决方案 > nuxt.js !process.server 永远不会进入 if 语句

问题描述

大家好,我有以下问题:

我有一个名为“仪表板”的 nuxt.js 页面,我为它制作了一个中间件,它看起来像这样:

export default {
   components: {
      overview
   },
   middleware: "authentication"
};

在我的 authentication.js 文件中:

  import axios from "axios";
  export default async function({ store, redirect }) {
  if (!store.state.authentication.authenticated) {
    if (!process.server) {
      console.log("i am in statement");
      if (!window.localStorage.getItem("realtime_jwt_token")) {
        return redirect("/");
      } else {
        const checkJwt = await axios.post("/api/checkToken", {
          token: window.localStorage.getItem("realtime_jwt_token")
        });
        if (checkJwt.data) {
          return null;
        }
        window.localStorage.removeItem("realtime_jwt_token");
        return redirect("/");
      }
    }
  }
}

永远不会在我的浏览器中显示,console.log("i am in statement")也不会在服务器控制台上显示,我总是能够访问仪表板站点。为什么!process.server在这里不起作用?

编辑:

我发现了原因。

如果您将模式设置为“通用”,中间件会在服务器端运行一次。要访问客户端,您应该将模式设置为“spa”,或者您寻找其他解决方案

标签: javascriptvue.jsnuxt.js

解决方案


您可能不是对 process.server 有问题,而是对前面的语句“store.state.authentication.authenticated”有问题。您是否使用上面的另一个 console.log 进行了检查?


推荐阅读