简体   繁体   中英

How to pass request body into GraphQL Context?

I'm currently attempting to get the request body into context, because part of the body contains a JWT that needs to be decoded. However when I try the following I get undefined for context:

    app.use('/', graphqlHTTP((req) => ({
      schema: Schema,
      context: req.body,
      pretty: true,
      graphiql: false
    })));

I logged out req and I didn't see body in there. I'm using a library called react-reach , it adds the following to the body on the request:

    {
      query: {...},
      queryParams: {...},
      options: {
       token: '...' // <-- I'm passing the token into options
      }
    }

I know the body is being interpreted because my queries/mutations that are in the body are being interpreted and executed. Just can't seem to find it when passed to context.

Your req.body is undefined unless you're using additional body-parser middleware. From the Express documentation:

req.body

Contains key-value pairs of data submitted in the request body. By default, it is undefined, and is populated when you use body-parsing middleware such as body-parser and multer. http://expressjs.com/en/api.html#req.body

graphqlHTTP is doing it's own thing to parse the request body (see here ) and that's why your queries/mutations are working.

Adding middleware (like body-parser or multer) to parse the request body should make it available on req.body and then your context should become populated with what you're looking for.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM