Javascript 节点中的摘要(req、res、next)
假设我有一条路线:Javascript 节点中的摘要(req、res、next),javascript,node.js,Javascript,Node.js,假设我有一条路线: app.get(abc, (req, res, next) => { if (req.params.ID === undefined) { res.status(400); res.end(); } next(); }); 我想知道,如果我将if语句抽象到另一个文件中,这样做是否也同样有效: let undefinedID = (req, res, next) => { if (req.par
app.get(abc, (req, res, next) => {
if (req.params.ID === undefined) {
res.status(400);
res.end();
}
next();
});
我想知道,如果我将if语句抽象到另一个文件中,这样做是否也同样有效:
let undefinedID = (req, res, next) => {
if (req.params.ID === undefined) {
res.status(400);
res.end();
}
next();
}
module.exports = {undefinedID};
然后在我的路线内调用函数:
const reqConditionals = require('path/to/fxn');
app.get(abc, () => {
reqConditionals.undefinedID();
});
我之所以要这样做,是因为我有许多具有类似请求条件和响应的路由,并且希望开始重构它。那么,如果我这样做的话,它是否也会起同样的作用呢?是的,你可以这样做。但你是这样做的:
const reqConditionals = require('path/to/fxn');
app.get(abc, reqConditionals.undefinedID);
然后你可以得到实际的路线
app.get(abc, reqConditionals.undefinedID);
app.get(abc, (req, res, next) => {
//here you know that the id is not undefined cause the previous middleware let you reach here.
});
此外,您可以将其应用于数组或其他任何对象,并具有多个函数
app.get([abc, def], reqConditionals.undefinedID, reqConditionals.undefinedFoo, reqConditionals.undefinedBar);
太棒了,谢谢你的快速回复!这就非常清楚了。我会尽快接受这个答案:)你需要
在res.end()之后返回
,如果你进入if语句,即使我像yBrodsky下面说的那样做,我也需要它吗?是的。如果您end()。但是,最好调用next(someErr)
并使用错误处理程序。