Express.js-是否有一种方法可以使用带有req,res对象的辅助函数

coo*_*ool 3 javascript connect node.js express

如何为带有内置req,res对象的路由提供帮助功能。例如 如果我在json中发送了错误或成功消息,则有以下几行代码

    console.log(err)
    data.success = false
    data.type = 'e'
    data.txt = "enter a valid email"
    res.json data
Run Code Online (Sandbox Code Playgroud)

我打算将其放在这样的辅助函数中

global.sendJsonErr = (msg)->
        data.success = false
        data.type = 'e'
        data.txt = msg
        res.json data
Run Code Online (Sandbox Code Playgroud)

但是我在辅助函数中没有res对象,除了传递它之外,我如何获得这些对象。由于将有更多重复的代码出现,所以我想走这条路。它是一种宏,而不是功能模块。谢谢

Jer*_*Orr 5

我已经编写了自定义中间件来做类似的事情。像这样:

app.use(function(req, res, next) {
  // Adds the sendJsonErr function to the res object, doesn't actually execute it
  res.sendJsonErr = function (msg) {
    // Do whatever you want, you have access to req and res in this closure
    res.json(500, {txt: msg, type: 'e'})
  }

  // So processing can continue
  next() 
})
Run Code Online (Sandbox Code Playgroud)

现在您可以执行以下操作:

res.sendJsonErr('oh no, an error!')
Run Code Online (Sandbox Code Playgroud)

有关编写自定义中间件的更多信息,请参见http://www.hacksparrow.com/how-to-write-midddleware-for-connect-express-js.html