我正在用 node.js 中的 express 撰寫超時中間件。
app.use((req, res, next) => {
res.setTimeout(3000, () => {
console.warn("Timeout - response end with 408")
res.status(408).json({ "error": "timeout 408" });
// !!! error will happen with next function when call like `res.send()`:
// Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
next()
})
如果有一個端點需要超過 3000 毫秒,我的中間件將回應 408。但是,下一個函式將再次回應。我不想res.headersSent每次都檢查 api 是否已經發送了回應。
有沒有更好的方法來處理這個問題——就像標題所說的那樣——取消中間件中的下一個回應?
uj5u.com熱心網友回復:
這是您自己的回應處理程式中仍在運行的代碼(可能正在等待某些異步操作完成)。沒有辦法告訴解釋器停止從該代碼之外運行該代碼。Javascript 沒有該功能,除非您將該代碼放在 WorkerThread 或單獨的行程中(在這種情況下,您可以終止該執行緒/行程)。
如果您只是在代碼最終嘗試發送其回應時(在已發送超時回應之后)試圖抑制該警告,您可以執行以下操作:
app.use((req, res, next) => {
res.setTimeout(3000, () => {
console.warn("Timeout - response end with 408")
res.status(408).json({ "error": "timeout 408" });
// to avoid warnings after a timeout sent,
// replace the send functions with no-ops
// for the rest of this particular response object's lifetime
res.json = res.send = res.sendFile = res.jsonP = res.end = res.sendStatus = function() {
return this;
}
});
next();
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/459238.html
標籤:javascript 节点.js 表示
