【发布时间】:2020-06-01 22:24:40
【问题描述】:
您好,我面临的问题是我需要在数据库中记录每个传入请求和相关响应。我当前的解决方案如下所示:
./routes/customer.js
router.get('/', async (req, res, next) => {
req.allCustomers = await fetchAllCustomers();
res.status(200).send(req.allCustomers);
next(); // <- this is my personal problem
});
./middleware/logging.js
module.exports = function (req, res, next) {
db.query(
`INSERT INTO logging SET ?`,
{
request: JSON.stringify([req.body, req.params]),
response: JSON.stringify(req.response)
}
);
}
路由声明
module.exports = function(app) {
app.use(express.json());
app.use('/api/customers', customers); // <- ROUTE ./routes/customer.js
app.use(logging); // <- MIDDLEWARE ./middleware/logging.js
}
我已经在我的第一段代码中提到了我的问题。在每条路线中手动调用next() 确实是重复的,我想避免这种情况。我已经尝试在所有路由之前加载中间件,在中间件函数中调用next(),然后执行我的数据库查询,但由于异步功能,我此时没有响应。
有什么办法可以处理这种情况,还是我需要在每个路由函数结束时继续调用next()?
【问题讨论】:
标签: javascript node.js express routes