我在我的
graphql
应用程序上使用 Apollo 客户端作为 next.js
客户端,这是为我创建客户端的函数:
let client: ApolloClient<any>;
export const __ssrMode__: boolean = typeof window === "undefined";
export const uri: string = "http://localhost:3001/graphql";
const createApolloClient = (): ApolloClient<any> => {
return new ApolloClient({
credentials: "include",
ssrMode: __ssrMode__,
link: createHttpLink({
uri,
credentials: "include",
}),
cache: new InMemoryCache(),
});
};
令人惊讶的是,当我对 graphql 服务器进行更改时,我能够设置 cookie,但是我无法从客户端获取 cookie。可能是什么问题?
我遇到了同样的问题,我的解决方案是每次进行服务器端渲染时都创建一个客户端,也许让客户端在浏览器中执行 GraphQL 调用并在服务器中执行其他调用并不理想,但这是最好的为我。这是代码:
import { ApolloClient, createHttpLink, InMemoryCache } from '@apollo/client';
import { NextPageContext } from 'next';
import { setContext } from '@apollo/client/link/context';
export const httpLink = createHttpLink({
uri: 'http://localhost:4000/graphql',
credentials: 'include',
});
const CreateClient = (ctx: NextPageContext | null) => {
const authLink = setContext((_, { headers }) => {
return {
headers: {
...headers,
cookie:
(typeof window === 'undefined'
? ctx?.req?.headers.cookie || undefined
: undefined) || '',
},
};
});
return new ApolloClient({
credentials: 'include',
link: authLink.concat(httpLink),
cache: new InMemoryCache(),
ssrMode: true,
});
};
export default CreateClient;
所以,我所做的是从 getServerSideProps 传递上下文,看看我那里是否有一些 cookie,如果有,我只是设置 cookie,如果它在 cookie 中,您也可以发送授权令牌。调用它很简单:
export async function getServerSideProps(context: NextPageContext) {
const client = CreateClient(context);
const { data } = await client.query({
query: SOME_QUERY,
});
return {
props: {
data,
},
};
}
您也可以像 Ben Awad 教程 Apollo Client HOC 那样做一个 HOC,但我认为这对我想做的事情来说太多了。希望它能帮助你或帮助那里的人 :)
此外,我正在使用 Next 12.1.5 和 React 18
我有同样的问题。 有了之前的回答,确实可以解决,但是我不是很服气
我的解决方案如下(我没有找到可以澄清的地方,但这是反复试验)
Apollo 客户端配置:
import {ApolloClient, HttpLink, InMemoryCache} from "@apollo/client";
const httpLink = new HttpLink({
uri: `${process.env.NEXT_PUBLIC_URL_SITE}/api/graphql`,
credentials: "same-origin",
});
export const client = new ApolloClient({
link: httpLink,
cache: new InMemoryCache(),
});
SSR请求:
export const getServerSideProps: GetServerSideProps = async ({req}) => {
const {data} = await client.query({
query: QUERY_NAME,
context: {
headers: {
cookie: req?.headers?.cookie ?? null,
},
},
});
return {
props: {data},
};
};
你必须手动添加 上下文:{ 标题:{ cookie: req?.headers?.cookie ??无效的, }, },
我在用: