如何解决“运行`getDataFromTree`时出错网络错误:未定义localStorage”?

时间:2019-07-25 07:47:25

标签: passport.js google-oauth2 next.js apollo-client

一切正常,但我一直在获取:运行getDataFromTree时出错网络错误:未定义localStorage。我试着有条件地只从客户端发送请求,但没有用。所有请求似乎都来自服务器。

我正在使用Google Oauth和护照在NextJS中进行身份验证

我应该从其他文件创建authLink吗?有任何线索吗?

使用完整链接: https://www.apollographql.com/docs/react/recipes/authentication/ https://github.com/zeit/next.js/tree/canary/examples/with-apollo

我试图将条件逻辑仅从客户端发送请求,但随后逻辑停止工作。看起来大多数nextJS请求来自服务器端。

 let apolloClient = null

    const authLink = setContext((_, { headers }) => {

    // get the authentication token from local storage if it exists
    const token = localStorage.getItem('token');
    // return the headers to the context so httpLink can read them
    return {
      headers: {
        ...headers,
        authorization: token ? Bearer ${token} : "",
       }
      }
   });

    function create(initialState) {
    // Check out https://github.com/zeit/next.js/pull/4611 if you want to use the AWSAppSyncClient
    const isBrowser = typeof window !== 'undefined'

    console.log(isBrowser);
    return new ApolloClient({
    connectToDevTools: isBrowser,
    ssrMode: !isBrowser, // Disables forceFetch on the server (so queries are only run once)
    link: authLink.concat(new createHttpLink({
    uri: 'http://localhost:3000/graphql', // Server URL (must be absolute)
    credentials: 'same-origin', // Additional fetch() options like credentials or headers
    // Use fetch() polyfill on the server
    fetch: !isBrowser && fetch
    })),
    cache: new InMemoryCache().restore(initialState || {})
    })
    }

    export default function initApollo(initialState) {
    // Make sure to create a new client for every server-side request so that data
    // isn't shared between connections (which would be bad)
    if (typeof window === 'undefined') {
    return create(initialState)
    }

    // Reuse client on the client-side
    if (!apolloClient) {
    apolloClient = create(initialState)
    }

    return apolloClient
    }

我需要apollo随每个请求发送cookie,以便我的react组件可以查找用户是否已登录。

我很伤心,不胜感激。预先谢谢你。

0 个答案:

没有答案