2016-07-29 83 views
1

我想保存我的服務器提供的4XX和5XX錯誤的數量。我採取的方法是創建一個明確的中間件獲得的StatusCode響應如何訪問發送到Expressjs應用程序客戶端的響應代碼

const fooMiddleware = (req, res, next) => { 
    req.stats.totalRequestsServed += 1; 

    // I want to access the status code sent to the client here 
    console.log('status code', res.statusCode); 
    next(null); 
}; 

我在上面使用的代碼,但我總是得到一個200狀態代碼,即使我在我的路線上硬編碼res.status(401).end()

回答

1

你的答案可以發現here

app.use(function (req, res, next) { 
    function afterResponse() { 
     res.removeListener('finish', afterResponse); 
     res.removeListener('close', afterResponse); 

     // do smth after res.send 
     console.log(res.status); 
    } 

    res.on('finish', afterResponse); 
    res.on('close', afterResponse); 

    // do smth before request eventually calling `next()` 
    next(); 
}); 

恕我直言,勾手不透明度。這需要一些「特殊」情況。
對於記錄4xx和5xx錯誤,錯誤處理程序更好。

app.get('/smth', function(req, res, next){ 
    if (!smth-check) 
     return next(new HttpError(401, 'Error-text')); // it's custom error class 
    ... 
}) 

app.use(function(err, req, res, next)) { 
    if (err instance of HttpError) 
     console.log(err.status); 
    ... 
}); 

關於custom errorHttpError您可以閱讀here

+0

第二種方法的問題是我們並不總是使用next。我喜歡更獨立的解決方案。 –

0

我發現了一個叫做on-finished是管理,這也增加了聽衆。它可以像這樣使用:

const onFinished = require('on-finished'); 

const middleware = (req, res, next) => { 

    onFinished(res, (err, res) => { 
    // do smth after res.send 
    }); 

    // do smth before request eventually calling `next()` 
    next(null); 
}; 
0

你的邏輯是正確的,你只需要調用next之前獲得的狀態,讓其他中間件/路線可以設置狀態碼:

const fooMiddleware = (req, res, next) => { 
    req.stats.totalRequestsServed += 1; 
    next(); 
    console.log('status code', res.statusCode); 
}; 
相關問題