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

cri*_*ari 0 express apollo graphql server-side-rendering next.js

graphql我在我的应用程序上使用 Apollo Client 作为客户端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(),
  });
};
Run Code Online (Sandbox Code Playgroud)

令人惊讶的是,当我对 graphql 服务器进行更改时,我能够设置 cookie,但是我无法从客户端获取 cookie。可能是什么问题?

小智 5

我遇到了同样的问题,我的解决方案是每次进行服务器端渲染时创建一个客户端,也许让客户端在浏览器中执行 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;
Run Code Online (Sandbox Code Playgroud)

所以,我所做的就是从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,
    },
  };
}
Run Code Online (Sandbox Code Playgroud)

您也可以像 Ben Awad 教程Apollo Client HOC中那样执行 HOC ,但我认为这对于我想要做的事情来说太多了。希望它能帮助你或帮助那里的人:)

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