[Fixed] GraphQL – POST body missing. Did you forget use body-parser middleware?

Issue

I keep getting the following error on my graphql queries and not sure why:

POST body missing. Did you forget use body-parser middleware?

Am I doing something weird here? I have tried different recommendations with body-parser online, but still can’t seem to fix it.

Server:

require('babel-polyfill')

const express = require('express')
const router = require('./middleware')
const expressStaticGzip = require('express-static-gzip')
const app = express()
const port = process.env.EXPRESS_PORT || 4000
const bodyParser = require('body-parser')

app.use(/\/((?!graphql).)*/, bodyParser.urlencoded({ extended: true }))
app.use(/\/((?!graphql).)*/, bodyParser.json())
app.use('/search/data', expressStaticGzip('public'))
app.use('/', router)

app.listen(port, () => {
  console.log(`Server is running on port ${port}`)
})

Router


const router = express.Router()
const server = new ApolloServer({
  typeDefs,
  resolvers,
  context: ({ req }) => {
    const { authorization = '' } = req.headers
    const universalFetch = (url, opts = {}) => {
      return fetch(url, {
        ...opts,
        headers: {
          ...opts.headers,
          authorization,
        },
      })
    }
    const request = createRpcClient(universalFetch)

    const methods = {}

    const catalog = Object.keys(methods).reduce((catalog, method) => {
      catalog[method] = params => request(methods[method], params)
      return catalog
    }, {})
    return { catalog, fetch: universalFetch }
  },
})

router.use(bodyParser.json())
router.use(bodyParser.text({ type: 'application/graphql' }))
router.use('*', renderer)
server.applyMiddleware({ app: router })

Solution

applyMiddleware already adds body-parser for the GraphQL endpoint — there’s no need to apply it again and doing so may be causing your issue.

Additionally, I would expect applyMiddleware to be called before router.use('*', renderer) — otherwise, I would think the wildcard route would be used for /graphql as well?

Leave a Reply

(*) Required, Your email will not be published