【问题标题】:Retrieving non-header context from Apollo Server从 Apollo Server 检索非标头上下文
【发布时间】:2020-12-22 03:38:06
【问题描述】:

我不断看到关于在 Apollo Client 上设置上下文的示例:

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

包含进入请求标头的内容和“其他”内容。然而,经过 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 和一个res 对象。经过一些日志,它似乎没有包含我想要的数据。

谢谢。

【问题讨论】:

    标签: javascript apollo react-apollo apollo-client apollo-server


    【解决方案1】:

    在您共享的示例中显示标头共享的唯一原因是ApolloClient 在其上下文中使用headers 值来填充它在发出请求时发送的HTTP headers。然后这些标头由express 解析并在req 对象上可用。 ApolloClient 使用的上下文是严格的客户端。 ApolloServer 使用的上下文严格是服务器端的。您不能使用 ApolloClient 的上下文将任意值传递给您的服务器——您应该在 GraphQL 查询中使用标头或参数。

    【讨论】:

      猜你喜欢
      • 2021-09-02
      • 2023-04-05
      • 1970-01-01
      • 2019-01-21
      • 2020-11-08
      • 2017-07-19
      • 2012-12-19
      • 2019-07-15
      • 1970-01-01
      相关资源
      最近更新 更多