![](/img/trans.png)
[英]Express.js Automatically append key:value to res.send()
[英]Express.js - Get the res.send value
我的問題正是這個 。 問題是,當我將解決方案應用於該問題時,什么也沒發生-res.send的值未記錄。 我使用快遞4.16.4。
這是我的代碼:
/* FILE: /app.js: */
...
const postRoute = require('./middleware/postRoute');
const myRoute = require('./routes/myRoute');
...
app.use('/', myRoute);
app.use(postRoute);
...
/* FILE: /routes/myRoute */
...
router.post('/myRoute', [], (req, res, next) => {
res.send({ status:'success', message:'Test success. Feels good, man.' });
next();
});
...
/* FILE: /middleware/postRoute */
const postRoute = function(req, res, next) {
console.log('postRoute: ');
var send = res.send;
res.send = function(chunk, encoding){
res.send = send;
if (chunk) {
console.log('postRoute chunk: ', chunk); // This statement is never reached
}
res.send(chunk, encoding);
};
next();
};
module.exports = { postRoute };
當我使用Postman向/myRoute
postRoute:
發出POST
請求時,它會記錄以下內容: postRoute:
此而已。 永遠不會到達第二個console.log()
並且可能與console.log()
相同的function()
中的任何其他語句也不會到達。
我在問題開始時鏈接到的問題是2015年,當時我假設他們使用了不同版本的Express.js,這就是為什么他們的解決方案對我不起作用的原因? 在我的中間件代碼示例中,我使用了與該問題的答案之一相關聯的問題代碼,因為該解決方案對我不起作用。 但是該解決方案顯然也不起作用,否則我不會在這里-這是從2012年開始的! 誰甚至不知道他們當時使用的Express版本!?
因此,重申並總結我的問題:如何使用中間件記錄傳遞給res.send()
的值?
跟進問題(但讓我知道是否寧願在另一個問題中問這個問題):有沒有一種方法可以在路由/響應之后從路由而不是全局調用中間件。 所以router.post('/myRoute', [postRoute], (req, res, next) => {...});
而不是app.use(postRoute)
?
這就是我最終要做的。 我保持文件結構完全相同,但是我沒有將路由中的res.send()
附加到res
對象中,而是在路由末尾調用了next()
。 因此,例如, res.send({message:'blah'});
變成res.return = {message:'blah'}; next();
res.return = {message:'blah'}; next();
。 我使用.return
是因為我不相信默認情況下res
對象上會存在這樣的屬性,並且我發現它足以描述我的目的。 然后,在我的postRoute
中間件中,我可以輕松訪問res.return
,然后調用return res.send(res.return)
。
使用我的問題示例( app.js
完全與您看到的一樣):
/* FILE: /routes/myRoute */
...
router.post('/myRoute', [], (req, res, next) => {
if(theConditionIsMet()) {
res.return = { message:'The condition was met.' };
} else {
res.return = { message:'The condition was not met.' };
}
next();
});
....
router.post('/anotherRoute', [], (req, res, next) => {
// In this route I don't need to intercept the response, so I just do it like normal.
return res.send({ message:'Feels good, man.' });
});
...
/* FILE: /middleware/postRoute */
const postRoute = function(req, res, next) {
if(res.hasOwnProperty('return') {
return res.send(res.return);
}
};
module.exports = { postRoute };
我已經看到的一個缺陷是,我現在必須重組所有路由以使用此res.send()
方法(或至少要截取返回值的所有路由)。 因此,並且因為我認為比我更博學的人可能會找到一種更好的方法,所以我不會接受自己的答案。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.