Apollo 客户端上下文中没有标头

No Headers in Apollo Client Context

提问人:Pierre Olivier Tran 提问时间:11/7/2023 更新时间:11/7/2023 访问量:17

问:

我在应用中使用基于 Cookie 的身份验证。为了验证我的请求,我想出了这段代码:

import { HttpLink } from "@apollo/client";
import { setContext } from "@apollo/client/link/context";
import { ACCESS_TOKEN_COOKIE_NAME } from "constants/cookies";
import { getCookie } from "./cookies";

const apiBaseUrl = process.env.NEXT_PUBLIC_API_BASE_URL;

// eslint-disable-next-line import/prefer-default-export
export const getApolloClientLink = () => {
  const httpLink = new HttpLink({
    uri: `${apiBaseUrl}/graphql`,
    // Pass credentials to the server
    credentials: "same-origin",
  });

  const authLink = setContext(async (_, { headers }) => {
    console.log("Current headers", headers);

    // Get the authentication token from apollo context if it exists
    const existingToken = headers?.authorization;

    if (existingToken) {
      console.log("WE HAVE A TOKEN", existingToken);
      return {
        headers: {
          ...headers,
          authorization: existingToken,
        },
      };
    }

    console.log("NO TOKEN");
    // If no token is found, get it from cookies
    const token = await getCookie(ACCESS_TOKEN_COOKIE_NAME);

    console.log("updated headers:", {
      headers: {
        ...headers,
        authorization: token ? `Bearer ${token.value}` : "",
      },
    });

    // return the headers to the context so httpLink can read them
    return {
      headers: {
        ...headers,
        authorization: token ? `Bearer ${token.value}` : "",
      },
    };
  });

  return authLink.concat(httpLink);
};

这为我提供了它传递给我的 apollo 客户端的链接:

export const { getClient } = registerApolloClient(
  () =>
    new NextSSRApolloClient({
      cache: new NextSSRInMemoryCache(),
      link: getApolloClientLink(),
    }),
);

不幸的是,它总是记录“NO TOKEN”,并且在记录我的标头的值时,它总是返回 undefined。我错过了什么吗?

下一个.js apollo客户端

评论

0赞 Bergi 11/7/2023
如果您正在执行基于 cookie 的身份验证,为什么需要发送标头?只需在后端使用会话 cookie 即可。authorization

答:

0赞 phry 11/7/2023 #1

这些标头是 Next 服务器发送到 GraphQL 服务器的请求标头 - 它们与浏览器发送到 Next 服务器的请求标头没有任何关系。为此,您必须使用 Next.js 和函数。headers()cookies()