Expressjs - 有没有办法使用req,res对象获得辅助函数

时间:2013-07-03 12:09:36

标签: javascript node.js express connect

如何为内置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对象,除了传递它之外,我怎样才能获得这些对象。因为会有更多重复的代码,我想要走出路线。 它是一种宏而不是功能模块。 谢谢

2 个答案:

答案 0 :(得分: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() 
})

现在你可以这样做:

res.sendJsonErr('oh no, an error!')

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

答案 1 :(得分:1)

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

这里定义了一些示例:http://www.hacksparrow.com/how-to-write-midddleware-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(); }
}