问题出现是因为Next.js的getServerSideProps在后端执行,而Apollo客户端使用的是浏览器中的SchemaLink。但是我们可以通过一些修改来解决这个问题。
第一步:创建一个Apollo Provider并将客户端传递给它
import { ApolloClient, InMemoryCache, ApolloProvider } from '@apollo/client';
const client = new ApolloClient({ uri: 'http://localhost:3000/api/graphql', cache: new InMemoryCache() });
export default function App({ Component, pageProps }) {
return (
第二步:使用Apollo客户端来查询数据
export const getServerSideProps = async (context) => {
const { data } = await client.query({
query: gql query { helloWorld }
,
});
return { props: { helloWorld: data.helloWorld, }, }; };
通过这个方法,我们现在可以在Next.js的getServerSideProps中使用Apollo客户端来查询数据了。