如何使用内置的 req,res 对象为路由提供辅助函数。例如。如果我在 json 中发送了错误或成功消息,我有以下代码行
console.log(err)
data.success = false
data.type = 'e'
data.txt = "enter a valid email"
res.json data
我打算把它放在这样的辅助函数中
global.sendJsonErr = (msg)->
data.success = false
data.type = 'e'
data.txt = msg
res.json data
但我在辅助函数中没有 res 对象,我如何才能获得这些对象,而不是传递它。因为会有更多的重复代码,所以我想去掉这条路线。 它更像是一种宏而不是功能模块。 谢谢
最佳答案
我编写了自定义中间件来做类似的事情。像这样:
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()
})
现在你可以这样做了:
res.sendJsonErr('oh no, an error!')
参见 http://www.hacksparrow.com/how-to-write-midddleware-for-connect-express-js.html有关编写自定义中间件的更多信息。
关于javascript - Expressjs - 有没有办法让 req,res 对象有辅助函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17447570/