簡體   English   中英

為 NextJS 實現 Apollo 客戶端,但無法讀取未定義的屬性“WebSocket”

[英]Implementing Apollo Client for NextJS but getting Cannot read property 'WebSocket' of undefined

在看了各種視頻和閱讀文章后,決定從普通的 React 切換到 NextJS。 我目前正在嘗試實現 Apollo Client,但收到此(標題)錯誤並希望獲得一些幫助。 我的 withData 當前設置的方式是

import { ApolloClient } from 'apollo-client';
import { ApolloLink } from 'apollo-link';
import { InMemoryCache } from 'apollo-cache-inmemory';
import { createHttpLink } from 'apollo-link-http';
import { setContext } from 'apollo-link-context';
import { hasSubscription } from '@jumpn/utils-graphql';
import * as AbsintheSocket from '@absinthe/socket';
import withApollo from 'next-with-apollo';
import { createAbsintheSocketLink } from '@absinthe/socket-apollo-link';
import { Socket as PhoenixSocket } from 'phoenix';

let apolloClient = null;

const HTTP_ENDPOINT = 'http://localhost:4000/api/v1/graphiql';

const WS_ENDPOINT = 'ws://localhost:4000/api/v1/socket';

const httpLink = createHttpLink({
    url: HTTP_ENDPOINT
});

const socketLink = createAbsintheSocketLink(AbsintheSocket.create(new PhoenixSocket(WS_ENDPOINT)));

const authLink = setContext((_, { headers }) => {
    const token = localStorage.getItem('auth-item');
    return {
        headers: {
            ...headers,
            authorization: token ? `Bearer ${token}` : ''
        }
    };
});

const link = new ApolloLink.split(
    (operation) => hasSubscription(operation.query),
    socketLink,
    authLink.concat(httpLink)
);

const create = (initialState) => {
    return new ApolloClient({
        link: link,
        cache: new InMemoryCache().restore(initialState || {})
    });
};

const 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;
};

export default withApollo(initApollo);

感謝所有幫助,以了解我做錯了什么,如果有更好的方法是什么。

問題是因為 nextJs 將在服務器中運行上面的代碼,並且WebSocket是僅存在於瀏覽器中的屬性,要修復此問題,您可以執行以下操作:

const socketLink =
  process.browser &&
  createAbsintheSocketLink(
    AbsintheSocket.create(
      new PhoenixSocket(WS_URI)
    )
  )

通過檢查process.browser ,您可以確保此 function 僅在客戶端執行。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM