【问题标题】:Nuxt window is not defined on server-side renderingNuxt 窗口未在服务器端渲染上定义
【发布时间】:2017-12-30 15:11:27
【问题描述】:

我正在尝试从我的中间件中的 localStorage 获取授权标头。不幸的是,这在第一个页面加载时不起作用,因为它是服务器渲染的。

我该如何解决这个问题?

const cookieName = 'feathers-jwt';
import { ApolloClient, createNetworkInterface } from 'apollo-client';
import 'isomorphic-fetch';

const API_ENDPOINT = 'http://localhost:3000/graphql';

const networkInterface = createNetworkInterface({ uri: API_ENDPOINT });

networkInterface.use([{
  applyMiddleware(req, next) {
    if (!req.options.headers) {
      req.options.headers = {};  // Create the header object if needed.
    }
    req.options.headers['authorization'] = window.localStorage.getItem(cookieName);
    next();
  }
}]);

const apolloClient = new ApolloClient({
  networkInterface,
  transportBatching: true
});

export default apolloClient;

来源:http://dev.apollodata.com/core/network.html

【问题讨论】:

    标签: apollo-client nuxt.js server-rendering vue-server-renderer


    【解决方案1】:

    据我了解,当您在服务器上进行渲染时,您无法访问windowdocument。在服务器和客户端都呈现的应用程序中,您需要构建检查以查看您所在的位置,并相应地进行处理。

    您可以使用这个 sn-p 来检测您的位置:

    var canUseDOM = !!(
      typeof window !== 'undefined' &&
      window.document &&
      window.document.createElement
    )
    

    使用它来检查您是在运行服务器端还是客户端。在您的情况下,我会执行以下操作:

    1. 如果您是服务器端,则可以检查 HTTP 请求本身中的 cookie;
    2. 如果您是客户端,则可以查看您的 localStorage 商店。

    当然,您始终可以选择在服务器端默认将您的网站呈现为匿名未授权用户。但这会导致前端在授权状态下闪烁和闪烁,并且对用户来说很烦人。

    在您的情况下,我会尝试从您的 HTTP 请求中存在的实际 cookie 中查找授权 cookie。

    【讨论】:

    • 在哪里实现代码?你能举个例子吗?
    猜你喜欢
    • 2020-11-16
    • 2019-10-18
    • 2021-12-18
    • 1970-01-01
    • 1970-01-01
    • 2018-04-26
    • 2018-08-06
    • 2020-12-08
    • 1970-01-01
    相关资源
    最近更新 更多