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.
GraphQL requests can be sent via HTTP POST or HTTP GET requests. GET requests must be sent in the following format. The query, variables, and operation are sent as URL-encoded query parameters in the URL. In either request method (POST or GET), only query is required.
const filterType = new GraphQLObjectType ({ name: 'filterType', fields: { fieldName: { type: GraphQLString }, fieldValues: { type: GraphQLString }, filterType: { type: GraphQLString }, } }) const QueryType = new GraphQLObjectType({ name: 'Query', fields: () => ({ accounts: { type: new GraphQLList(accountType), args: { ...
In GraphQL, a context is an object shared by all the resolvers of a specific execution. It's useful for keeping data such as authentication info, the current user, database connection, data sources and other things you need for running your business logic.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With