Node.js Express.js控制台中未定义的内容来自何处?
用于测试目的的无用中间件:Node.js Express.js控制台中未定义的内容来自何处?,node.js,express,undefined,middleware,Node.js,Express,Undefined,Middleware,用于测试目的的无用中间件: module.exports = function () { return function rankick(req, res, next) { if (Math.random() < 0.5) { return next('Random kick...'); } next(); }; }; 当使用错误字符串调用next()时,控制台会记录undefined,然后是500
module.exports = function () {
return function rankick(req, res, next) {
if (Math.random() < 0.5) {
return next('Random kick...');
}
next();
};
};
当使用错误字符串调用next()
时,控制台会记录undefined
,然后是500
错误:
未定义
获得500/28毫秒
获取/200 4ms
未定义
获取/500 5ms
您应该这样做
module.exports = function rankick(req, res, next) {
if (Math.random() < 0.5) {
console.log('Random kick...');
}
else
next();
};
module.exports=函数rankick(req、res、next){
if(Math.random()<0.5){
console.log('Random kick…');
}
其他的
next();
};
不要使用return传递函数module.exports
是调用require时传递的对象
如果要继续处理到下一个中间件,还应该调用next()
。如果您想停止处理/kick请求,请不要调用next()
是的,它位于中的这一行。也许它希望得到一个新的错误(“随机踢…”)
我已经有一段时间没有使用默认的errorHandler了,所以我不是100%确定。如果不是否决票,我将删除此答案。使用favicon中间件上的Lootnext(err)
。next(err)
是错误处理,将错误传递给下一个中间件。如果你只是随意踢它们,那么就没有必要了。require('path')
位很愚蠢。它仅用于\uu dirname
行中的一行。可能没有必要,因为它所做的只是根据您的操作系统添加一个“/”或“\”,这在生产中不会改变。就我的2c
module.exports = function rankick(req, res, next) {
if (Math.random() < 0.5) {
console.log('Random kick...');
}
else
next();
};