正在从 Apollo 服务器检索 non-header 上下文

Retrieving non-header context from Apollo Server

我经常看到有关在 Apollo Client 上设置上下文的示例,如下所示:

new ApolloClient({
    uri: '...',
    request(operation) {
      const currentUser = readStore<CurrentUser>("currentUser");
      currentUser &&
        operation.setContext({
          headers: { authorization: currentUser.token },
          other: "things"
        });
    }
  });
}

关于请求 headers 的内容,以及“其他”内容。然而,经过 2 个多小时的研究,我找不到在 Apollo Server 的另一端检索其他上下文数据的示例。

似乎所有的例子都是关于授权令牌的,但是我如何检索其余的,比如使用 apollo-server-express ?

这是我目前的情况:

const apollo = new ApolloServer({
  typeDefs,
  resolvers,
  context({ req }): Context {
    const currentUser =
      (req.headers.authorization &&
        (jwt.verify(
          req.headers.authorization,
          process.env.JWTSIGN
        ) as Context["currentUser"])) ||
      null;

    // Ok for req.headers.authorization, how to I get "other: things" ?

    return {
      ip: req.ip,
      currentUser
    };
  }
});

这里的context函数只从Express获取了一个req和一个resobject。经过一些日志,里面好像没有我想要的数据。

谢谢。

它出现 headers 的唯一原因是在您共享的示例中被共享是因为 ApolloClient 在其上下文中使用 headers 值来填充它发送的 HTTP headers提出请求时。 headers 然后由 express 解析并在 req object 上可用。 ApolloClient 使用的上下文严格是 client-side。 ApolloServer 使用的上下文是严格的 server-side。您不能使用 ApolloClient 的上下文将任意值传递给您的服务器——您应该为此使用 headers 或 GraphQL 查询中的参数。