假设我有一条路线:
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);
关于javascript - Node 中的抽象 (req, res, next),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49158225/