首页 > 解决方案 > 特定中间件上的 bodyParser.json

问题描述

基本上,我需要对请求进行 bodyParse 以便能够使用 express-recaptcha,因此需要在该中间件中对其进行 bodyParse,但仅限于整个请求而不是整个请求。

这是我想要使用 bodyParser 的中间件(recaptcha.verify 期望它是 json 解析器):

const recaptchaMiddleware = function(req, res, next) {
  return recaptcha.verify(req, function(error, data) {
    logger.log({
      level: 'debug',
      message: 'Verifying recaptcha token',
    })
    if (error) {
      logger.log({
        level: 'error',
        message: `Error verifying recaptcha token for request`,
        body: error,
      })
      return res.status(403).send()
    }
    next()
  })
}

这是我的路线:

  .use(
    '/api/v1/mandrill',
    recaptchaMiddleware,
    function (req, res, next) {
      logger.log({
        level: 'debug',
        message: 'Debugme',
        body: JSON.stringify(req.body),
      })
      next()
    },
    createProxy(EMAIL_API, { onProxyRes: metricsMiddleware('emailservice', []) })
  )

我可以做以下悬停我代理的服务不喜欢那个....

    const jsonParser = bodyParser.json({ limit: '10mb' })

  .use(
    '/api/v1/mandrill',
    jsonParser,
    recaptchaMiddleware,
    function (req, res, next) {
      logger.log({
        level: 'debug',
        message: 'Debugme',
        body: JSON.stringify(req.body),
      })
      next()
    },
    createProxy(EMAIL_API, { onProxyRes: metricsMiddleware('emailservice', []) })
  )

摘要:我需要在 recaptcha.verify(req, function(error, data) 而不是整个路由上使用 bodyParser.json()

标签: node.jsexpressbody-parser

解决方案


推荐阅读