GraphQL - POST 正文丢失。您忘记使用 body-parser 中间件了吗?

Joh*_*son 8 node.js express reactjs graphql

我的查询中不断收到以下错误graphql,但不确定原因:

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

我在这里做了什么奇怪的事情吗?我已经尝试了在线 body-parser 的不同建议,但似乎仍然无法修复它。

服务器:

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}`)
})
Run Code Online (Sandbox Code Playgroud)

路由器


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 })
Run Code Online (Sandbox Code Playgroud)

Ily*_*iev 9

在我的特殊情况下,客户端只是错过了带有“application/json”值的“Content-type”标头。添加后,错误消息消失了。


Dan*_*den 3

applyMiddleware已经body-parser为 GraphQL 端点添加了——无需再次应用它,这样做可能会导致您的问题。

此外,我希望applyMiddleware之前被调用router.use('*', renderer)- 否则,我会认为通配符路由也会被使用/graphql