【问题标题】:Next.js: React Apollo Client Not sending cookies?Next.js:React Apollo 客户端不发送 cookie?
【发布时间】:2022-04-27 01:32:50
【问题描述】:

我在 next.js 应用程序上使用 Apollo Client 作为 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。可能是什么问题?

【问题讨论】:

    标签: express graphql next.js apollo server-side-rendering


    【解决方案1】:

    我遇到了同样的问题,我的解决方案是每次进行服务器端渲染时都创建一个客户端,也许让客户端在浏览器中执行 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,如果它在曲奇饼。调用它很简单:

    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

    【讨论】:

      猜你喜欢
      • 2018-04-16
      • 2021-08-25
      • 2013-07-18
      • 1970-01-01
      • 2019-03-31
      • 1970-01-01
      • 1970-01-01
      • 2021-02-05
      相关资源
      最近更新 更多