How to transfer request body to GraphQL context?

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

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

I logged out and I did not see the body there. I use a library called react-reach , it adds the following to the request body:

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

I know that the body is interpreted because my requests / mutations that are in the body are interpreted and executed. It simply cannot find it when it is passed into context.

+5
source share
1 answer

Your req.body is undefined unless you use an additional binder for the parser body. From the Express documentation:

req.body

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

graphqlHTTP does this to check the request body (see here ) and why your requests / mutations work.

Adding middleware (e.g. body-parser or multer) to parse the request body should make it available on req.body , and then your context should be filled with what you are looking for.

+2
source

All Articles