【问题标题】:ExpressJS: Where to add bodyParser for middleware?ExpressJS:在哪里为中间件添加 bodyParser?
【发布时间】:2018-05-05 02:12:09
【问题描述】:

这就是我使用 bodyParser 作为 expressJS/graphQL 服务器的中间件的方式。

const graphqlMiddleware = [
  // bodyParser is needed just for POST.
  bodyParser.json(),
  bodyParser.text({ type: 'application/graphql' }),
  (req, res, next) => {
    res.header('Access-Control-Allow-Origin', '*')
    res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With')
    if (req.is('application/graphql')) {
      req.body = { query: req.body }
    }
    if (req.method === 'OPTIONS') {
      res.sendStatus(200)
    } else {
      next()
    }
  }
]

app.use('/graphql',
  ...graphqlMiddleware,
  graphqlExpress(req => ({
    schema: schema,
    rootValue: { db: req.app.locals.db }
  }))
)

现在我试图重组我的文件,所以我把函数移到了

/middlewares/graphql.js

module.exports = (req, res, next) => {
  res.header('Access-Control-Allow-Origin', '*')
  res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With')
  if (req.is('application/graphql')) {
    req.body = { query: req.body }
  }
  if (req.method === 'OPTIONS') {
    res.sendStatus(200)
  } else {
    next()
  }
}

...并将其导入我的入口点:

app.js

import graphqlMiddleware from './middlewares/graphql'

app.use('/graphql',
  graphqlMiddleware,
  graphqlExpress(req => ({
    schema: schema,
    rootValue: { db: req.app.locals.db }
  }))
)

但是我应该如何(以及在​​哪里)添加 bodyParser?

bodyParser.json(),
bodyParser.text({ type: 'application/graphql' })

【问题讨论】:

    标签: javascript express graphql


    【解决方案1】:
    ...
    app.use(bodyParser.json())
    
    app.use('/graphql',
      bodyParser.text({ type: 'application/graphql' }),
      graphqlMiddleware,
      graphqlExpress(req => ({
        schema: schema,
        rootValue: { db: req.app.locals.db }
      }))
    )
    ...
    

    【讨论】:

    • 不应该bodyParser.json()也只能添加到graphql吗?
    • 您只能将其添加到/graphql,但您可能会在应用程序的其他端点中需要它,因此您可以将其放在顶部
    猜你喜欢
    • 1970-01-01
    • 2012-01-18
    • 2017-06-20
    • 1970-01-01
    • 2023-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多