javascript - 如何在 express Router.route 和控制器模式中触发 next()?
问题描述
在请求到达我的 api 路由之一后,我似乎无法弄清楚如何实现“next()”。我想在一切完成后进行日志记录,而不是在我的 api 路由之前。我已经在我的路由上实现了控制器模式。我现在只能记录错误,但我想记录所有请求:
//------ api/index.js
import routes from './routes/index.route';
app.use('/api', routes);
// ??? HOW TO HANDLE next() called in "/api routes"
// only handles incoming requests not found in "/api routes"
app.use((req, res, next) => {
// logic here...
next(error);
});
// global error handler
app.use((error, req, res, next) => {
// logging logic here...
});
//------ routes/index.route.js
import express from 'express';
import userRoutes from './user.route';
import bookRoutes from './book.route';
const router = express.Router();
router.use('/user', userRoutes);
router.use('/book', bookRoutes);
//------ routes/book.route.js
import express from 'express';
import bookCtrl from './../controllers/book.controller';
const router = express.Router();
router.route('/:bookId').get(bookCtrl.getBook);
//------ controllers/book.controller.js
export const getBook = async (req, res, next) => {
const book = // get book logic here;
return res.status(httpStatus.OK).json(book);
// HOW DO I TRIGGER next()?
// I tried this approach as well:
// res.status(httpStatus.OK).json(book);
// next();
//however, it would say, "Error: Can't set headers after they are sent."
}
太感谢了。
解决方案
我想出了一种触发下一个的方法,它不会立即发送响应,而是将其分配给res.locals
并调用下一个。以下是基于我上面的代码的更改:
//------ api/index.js
// handle next() event coming from "/api routes"
// and also handles incoming requests not found in "/api routes"
app.use((req, res, next) => {
if (res.locals.status) {
const { status, responseData } = res.locals;
res.status(status).json(responseData);
// logging logic here...
} else {
// error logic here...
// forward this error into the global error handler
next(error);
}
});
// controllers/book.controller.js
export const getBook = async (req, res, next) => {
// get book logic here..
const book = // get book logic here;
res.locals = {
status: httpStatus.OK,
responseData: {
book,
},
};
next();
}
感谢 @destoryer 的 res.json 提示!:)
推荐阅读
- javascript - 使用从 ajax 请求返回的数据更新输入“值”属性...传入 [object, Object]。- Django/Python
- c - atomic operator++ 和 atomic_fetch_add_explicit 的区别
- python - 如何在布尔变量上使用 .trace?
- swift - 如何更快地显示来自 Firebase 的数据?
- r - 如何让R函数返回多个参数值
- python-3.x - 从 PyQt4 迁移到 PyQt5
- css - 在 RMarkdown 文档中为 fontcolor 创建与输出无关的标记
- java - 我有一个使用 H.264 (MPEG-4) 压缩记录视频的代码,但我想使用 MJPEG
- python - 如何访问/处理 TensorFlow 数据集中的内容?
- javascript - 在 Laravel 和 jquery 中删除文件的问题