用ExpressJS访问Apollo服务器中的请求对象[英] Accessing Request object in Apollo Server with ExpressJS

本文是小编为大家收集整理的关于用ExpressJS访问Apollo服务器中的请求对象的处理/解决方法,可以参考本文帮助大家快速定位并解决问题,中文翻译不准确的可切换到English标签页查看源文。

问题描述

有什么方法可以从 Apollo Server 中的底层 express 应用访问请求对象

推荐答案

上下文配置参数可以是对象,也可以是返回对象的函数,也可以是返回返回对象的promise的函数.该函数将 HTTP 请求作为参数获取,可以这样定义:

const apolloServer = new ApolloServer({
  schema,
  context: async ({ req }) => {
    const something = getSomething(req)
    return { something }
  },
})

apolloServer.applyMiddleware({ app, path: '/graphql' })

const { appPort } = serviceFunc.getAccessData()
app.listen({ port: appPort }, () => {
  console.log(`Express+Apollo Server on http://localhost:${appPort}/graphql`)
})

感谢 Eugene eugene1g

本文地址:https://www.itbaoku.cn/post/1938043.html

问题描述

Is there any way of accessing the request object from the underlying express app in Apollo Server

推荐答案

The context configuration parameter can be either an object, a function that returns the object, or a function that returns a promise to return the object. This function would get the HTTP request as a parameter, and could be defined like so:

const apolloServer = new ApolloServer({
  schema,
  context: async ({ req }) => {
    const something = getSomething(req)
    return { something }
  },
})

apolloServer.applyMiddleware({ app, path: '/graphql' })

const { appPort } = serviceFunc.getAccessData()
app.listen({ port: appPort }, () => {
  console.log(`Express+Apollo Server on http://localhost:${appPort}/graphql`)
})

Thanks to Eugene eugene1g