NextJS和React中阿波罗授权标头中的localStorage问题

时间:2020-03-13 19:05:17

标签: reactjs graphql next.js apollo

我使用this解决方案在NextJS和React项目中使用apollo客户端。

为什么不能在withApollo.js中使用localStorage?

我运行以下代码:

import withApollo from 'next-with-apollo';`
import ApolloClient, { InMemoryCache } from 'apollo-boost';
import { ApolloProvider } from '@apollo/react-hooks';

export default withApollo(
  ({ initialState }) => {
    return new ApolloClient({
      uri: 'http://localhost:8000/graphql/',
      cache: new InMemoryCache().restore(initialState || {}),
      headers: {
        authorization: localStorage.getItem("token")
      }
    });
  },
  {
    render: ({ Page, props }) => {
      return (
        <ApolloProvider client={props.apollo}>
          <Page {...props} />
        </ApolloProvider>
      );
    }
  }
);

我看到这个错误:

ReferenceError: localStorage is not defined
module.exports../lib/withApollo.js.__webpack_exports__.default.next_with_apollo__WEBPACK_IMPORTED_MODULE_1___default.render.Page.Page ./lib/withApollo.js:11

你能帮我吗?

0 个答案:

没有答案