Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 })
like image 484
John Lippson Avatar asked Dec 05 '19 17:12

John Lippson


4 Answers

In my particular case the client just missed "Content-type" header with 'application/json' value. After adding that the error message has dissapeared.

like image 94
Ilya Yevlampiev Avatar answered Oct 23 '22 06:10

Ilya Yevlampiev


This error also caused by incorrect json in the body or some other problems in the body, such as unnecessary wrong invisible chars. So check generated json for errors and what is actually presents in the request body.

like image 40
oklas Avatar answered Oct 23 '22 05:10

oklas


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?

like image 43
Daniel Rearden Avatar answered Oct 23 '22 05:10

Daniel Rearden


I forgot the header content-type: application/json

like image 30
Stev.dev Avatar answered Oct 23 '22 04:10

Stev.dev