3

如何使用内置的 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 对象,除了传递它之外,我怎样才能获得这些对象。由于会移动更多重复的代码,我想离开这条路线。它更像是一种宏而不是功能模块。谢谢

4

3 回答 3

6

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

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-middleware-for-connect-express-js.html

于 2013-07-03T12:39:09.840 回答
2

我不确切知道您的用例,但您可能想使用中间件。

此处定义的一些示例:http ://www.hacksparrow.com/how-to-write-middleware-for-connect-express-js.html但您可以拥有一个以 req 和 res 作为参数的函数,在每个请求时调用。

app.use(function(req, res) {
    res.end('Hello!');
});

您还可以访问第三个参数以将手传递给下一个中间件:

function(req, res, next) {
    if (enabled && banned.indexOf(req.connection.remoteAddress) > -1) {
        res.end('Banned');
    }
    else { next(); }
}
于 2013-07-03T12:27:41.393 回答
1

试试这个 reshelper

npm i reshelper
于 2022-01-04T05:32:17.463 回答