Expressjs-有没有一种方法可以让helper函数与req,res对象一起使用

Expressjs - Is there a way to have helper function with req,res object

本文关键字:req 函数 res 对象 一起 helper 有没有 一种 方法 Expressjs-      更新时间:2023-09-26

如何为内置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

但是我在helper函数中没有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有关编写自定义中间件的更多信息。

试试这个再帮助

npm i reshelper

我不知道你的具体用例,但你可能想使用中间件。

此处定义的一些示例: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(); }
}