Next.js: React Apollo 客户端不发送 cookie?

Next.js: React Apollo Client Not sending cookies?

我在 next.js 应用程序上使用 Apollo 客户端作为 graphql 客户端,这是为我创建客户端的函数:

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。可能是什么问题?

我遇到了同样的问题,我的解决方案是每次进行 server-side 渲染时都创建一个客户端,让客户端在浏览器中执行 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 教程中那样做一个 HOC Apollo Client HOC,但我认为这对我想做的事情来说太过分了。希望它能帮助你或帮助那里的人:)

此外,我正在使用 Next 12.1.5 和 React 18