如何在没有 express 的情况下为节点 graphql 解析器获取 header?

How can I get header for node graphql resolver without express?

我知道在快递中,我们可以有request.header,但是没有快递,我怎么能得到header?

我正在开发 Apollo 解析器,我正在尝试在我的 graphql 解析器中使用 header。

  async item (_, args, context) {
    if (ApiVersion === '2') {
      return await itemv2(args);
    }
    return await itemv1(args);
  },

As shown in the docs, the context parameter passed to ApolloServer's constructor can be either an object or a function. If it's a function, it should return the context object or a Promise that will resolve to one. The function is passed an object as its first parameter with a req property. This is an express request object 因为这就是 Apollo Server 在后台使用的内容。您可以访问通常在此 object 上可用的任何属性,包括 headers:

new ApolloServer({
  typeDefs,
  resolvers,
  context: ({ req }) => {
    console.log(req.headers.authorization)

    return req
  },
})

因此,如果您使用整个 req object 作为上下文,您可以执行以下操作:

  async item (_, args, context) {
    if (context.headers['api-version'] === '2') {
      return await itemv2(args);
    }
    return await itemv1(args);
  },