簡體   English   中英

express.js - 如何攔截 response.send() / response.json()

[英]express.js - how to intercept response.send() / response.json()

假設我有多個地方可以調用response.send(someData) 現在,我想創建一個單一的全球性的攔截,我捕捉所有.send方法和做一些改變someData express.js 有什么辦法嗎? (鈎子,偵聽器,攔截器,...)?

您可以定義一個中間件如下(從這個答案中獲取和修改)

function modifyResponseBody(req, res, next) {
    var oldSend = res.send;

    res.send = function(data){
        // arguments[0] (or `data`) contains the response body
        arguments[0] = "modified : " + arguments[0];
        oldSend.apply(res, arguments);
    }
    next();
}

app.use(modifyResponseBody);

對於那些在谷歌上找到的人,基於最佳答案:

app.use((req, res, next) => {
    let oldSend = res.send
    res.send = function(data) {
        console.log(data) // do something with the data
        res.send = oldSend // set function back to avoid the 'double-send'
        return res.send(data) // just call as normal with data
    }
    next()
})

是的,這是可能的。 有兩種方法可以做到這一點,一種是使用提供攔截的庫,並能夠根據特定條件運行它: https : //www.npmjs.com/package/express-interceptor

另一種選擇是創建您自己的中間件(用於 express),如下所示:

function modify(req, res, next){
  res.body = "this is the modified/new response";

  next();
}
express.use(modify);

只是想提供一個攔截res.json的實際使用示例。

在編寫 express 服務器時,我們可能會根據以下情況在每個響應中發送statusmessage

app.post('/test', (req, res) => {
    res.json({status: 1, message: "some_error", otherData: "nothing"})
})

但是,如果我不想每次都寫狀態和消息怎么辦? 我可以添加新函數來構建模板響應主體,以便在使用res.json時發送數據。

const messageMap = {
    0: "success",
    1: "some_error"
}

app.use((req, res, next) => {
    const originJson = res.json
    res.json = (status, jsonData) => {
        const fixedResponse = {
            status,
            message: messageMap[status]
        }
        originJson.call(res, {...jsonData, ...fixedResponse})
    }
    next()
})

然后我只需要使用下面的功能。

app.get("/test", (req, res) => {
    res.json(1, {otherData: 1})
})

您甚至可以使用構建器模式來執行此操作。

app.use((req, res) => {
    res.buildFixedResponse = function (status)  {
        const fixedResponse = {
            status,
            message: messageMap[status]
        }
        res.json = function (jsonData) {
            originJson.call(this, {...jsonData, ...fixedResponse})
        }
        return this
    }
})

然后觸發如下功能。

app.get("/test", (req, res) => {
    res.buildFixedResponse(1).json({otherData: 1})
})

就我而言,我必須使用帶有typicode/json-server的中間件,並且能夠獲得不同的響應對象,而不僅僅是一個簡單的 javascript 數組。

雖然typicode/json-server響應類似於:

[
 {
   ...
 }
]

應用中間件后:

module.exports = (req, res, next) => {
 const oldSend = res.send;
 res.send = (data) => {
  const oldData = JSON.parse(data);
  // we want to change the response only if a blunt array is sent
  // also, we do this for the old sake of not sending json arrays
  if(Object.prototype.toString.call(oldData) === '[object Array]') {
   data = {
    data: oldData
   };
  }
  res.send = oldSend;
  return res.send(data);
 };
 next();
}

響應如下所示:

 {
  data: [
   {
    ...
   }
  ]
 }

您可以簡單地使用 NODEJS 和 Express 來完成,假設您正在調用 API 並希望在發送響應之前發送修改數據。

router.get('/id', (req,res) => {
... //your code here filling DATA

  let testData = {
    "C1": "Data1",
    "C2": "Data2",
    "yourdata": DATA
  };          
  res.send(testData);
});

暫無
暫無

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

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