javascript - Expressjs - 有没有办法让 req,res 对象有辅助函数

标签 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 对象,我如何才能获得这些对象,而不是传递它。因为会有更多的重复代码,所以我想去掉这条路线。 它更像是一种宏而不是功能模块。 谢谢

最佳答案

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

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/

相关文章:

javascript - 创建一个脚本来增加网站上的数字

node.js - 如何在同一步骤中组合 ChoicePrompt 和 TextPrompt

sql-server - node.js:创建一个涵盖对多个存储库的调用的事务

node.js - 如何在 node.js Passport 身份验证上访问 POST 数据?

javascript - 上传文件夹(使用 FileSystem API)

javascript - 扩展 Javascript promise 并在构造函数中解决或拒绝它

node.js - 使用 NodeJS 连接接收文件

node.js - "Invalid csrf token"在nodejs(Express)中使用CSURF。CSRF token 对于第一个请求工作正常,但对于所有其他请求给出错误

javascript - Express用户认证中间件,应该做多少事情?

javascript - Javascript 库中的 mixin() 和 extend() 有什么区别