过滤掉特定路线的字段有什么好的做法?
我在考虑为端点A和B制作这个中间件:
module.exports.filterA = function (req, res, next) {
// filter out unwanted fields for A in req.body
next();
};
module.exports.filterB = function (req, res, next) {
// filter out unwanted fields for B in req.body
next();
};
然后我可以使用如下过滤器来确保端点A和B只允许在其特定字段中
router.post('/A', filterA, saveReqBodyToDatabase);
router.post('/B', filterB, saveReqBodyToDatabase);
我的策略是在req.body中删除任何不需要的东西,并最终将整个请求保存到数据库中,以便不为每条路径编写特定的保存方法......
答案 0 :(得分:0)
您可以使用
(tap)
或者,如果您只想保留一个或两个字段并删除其余字段:
module.exports.filterA = function (req, res, next) {
delete req.body.unwantedField1;
delete req.body.unwantedField2;
delete req.body.unwantedField3;
// filter out unwanted fields for A in req.body
next();
};