Nuxt窗口没有在服务器端渲染定义

问题描述:

我想从我的中间件内的localStorage获得授权头。不幸的是,这不适用于首页加载,因为它是服务器呈现的。Nuxt窗口没有在服务器端渲染定义

我该如何解决这个问题?

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

据我了解,当你渲染服务器上,你没有访问windowdocument。在服务器和客户端都呈现的应用程序中,您需要构建一个检查来查看您的位置,并据此处理。

您可以使用此代码段用于检测你在哪里:

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

用它来检查,如果你正在运行的服务器端或客户端。在你的情况下,我会做以下事情:

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

当然,您可以随时选择在服务器端将您的网站默认为匿名未授权用户。但是这会导致前端闪烁进入授权状态,并且会让用户烦恼。

就你而言,我会尝试从HTTP请求中存在的实际cookie中查找授权cookie。