簡體   English   中英

Expressjs - 有沒有辦法讓 req,res 對象具有輔助功能

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

如何為帶有內置 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

我不確切知道你的用例,但你可能想要使用中間件。

這里定義了一些示例: 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(); }
}

試試這個reshelper

npm i reshelper

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM