Javascript 如何在每个route函数中自动执行next()调用?(express.js)
您好,我面临的问题是,我需要在数据库中记录每个输入请求和相关响应。我当前的解决方案如下所示: /routes/customer.jsJavascript 如何在每个route函数中自动执行next()调用?(express.js),javascript,node.js,express,routes,Javascript,Node.js,Express,Routes,您好,我面临的问题是,我需要在数据库中记录每个输入请求和相关响应。我当前的解决方案如下所示: /routes/customer.js router.get('/', async (req, res, next) => { req.allCustomers = await fetchAllCustomers(); res.status(200).send(req.allCustomers); next(); // <- this is my personal
router.get('/', async (req, res, next) => {
req.allCustomers = await fetchAllCustomers();
res.status(200).send(req.allCustomers);
next(); // <- this is my personal problem
});
路线申报
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,然后执行我的db查询,但由于异步功能,此时没有响应
有没有办法处理这种情况,或者我需要在每个路由函数结束时继续调用next?当您像以前一样使用express.Router类,然后使用此代码时 应用程序。使用“/api/customers”,客户 如果不想从路由中调用next,则不能让中间件在它们之后运行。它需要放在前面。但是,您能在路由之前运行的中间件中得到响应吗?答案是肯定的 这可能有点黑客,但由于您的路由使用res.send,因此您可以将其用于您的优势。通过在路由之前运行,中间件可以劫持res.send函数,使其执行其他操作 /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
});
/中间件/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
}
我正面临着这个解决方案的一个重要问题。不可能使用req.params,也不包括响应。工作起来像个符咒。非常感谢!想知道为什么这不是节点的默认可能性。
function shouldBeLogged(req) {
// Here, check the route and method and decide whether you want to log it
console.log(req.method, req.path); // e.g. GET /api/customers
return true;
}
module.exports = function(app) {
app.use(express.json());
app.use(logging(shouldBeLogged)); // <- Place this before your routes
app.use('/api/customers', customers);
};