在观看了各种视频和阅读了文章后,决定从正常的React切换到NextJS。我目前正在尝试实现Apollo客户端,但遇到了这个(标题(错误,希望能得到一些帮助。当前设置我的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
,您可以确保此函数仅在客户端执行。