NodeJS Express在前一个路线之后发射全部路线

时间:2017-02-14 14:22:01

标签: node.js express routing middleware

我有一个基本的快速设置,包括以下内容:

app.all('/api/:controller/:id?', [ api, response.success, response.error ])

app.get('*', (req, res) => {
  console.log('This should only fire when no route matched')
  res.sendFile(path.resolve(pubRoot, 'index.html'))
})

在第一条路线上的中间件代码中,api模块此时只解析一个承诺(或拒绝404),然后调用next,这使得它成为响应中间件看起来像这样:

const response = {
  success: (req, res, next) => {
    res.status(200).send(res.data)
  },
  error: (error, req, res, next) => {
    const statusCode = error.statusCode || 500
    res.status(statusCode).send(error.message || 'Internal Server Error')
  }
}

这对成功的请求工作正常,我得到数据(和状态代码200)。它也适用于错误(按预期返回404Not Found),然而,它继续到通配符路由。我得到console.log以及Error: Can't set headers after they are sent.

更新:以下是api模块的代码:

const api = (req, res, next) => {
  const controller = req.params.controller
  const event = { body: req.body, id: req.params.id, query: req.query }
  // Handle non-existent controller
  if (!controllers[controller]) {
    next(new HTTPError(404))
    return
  }
  // Controller found, process
  controllers[controller][req.method.toLowerCase()](event)
    .then((result) => {
      res.data = result
      next()
    })
    .catch((err) => {
      next(err)
    })
}

0 个答案:

没有答案