Express中GET方法回调函数报错问题求助
Express GET请求报错问题排查与解决
我在使用Express框架开发时,.post、.patch、.delete方法均可正常运行,但调用.get方法时出现报错。
相关代码
tour.route.js
app.get(tour_controller.getTourById)
tour_controller.js
getTourById = handler.getOne(TourModel);
handler.js
exports.getOne = (Model, popOptions) => { catchAsync(async (req, res, next) => { let query = Model.findById(req.params.id); if (popOptions) { query = query.populate(popOptions); } const docs = await query; if (!docs) { return next( new apiError('No documents found with ID: ' + req.params.id, 404) ); } res.status(200).json({ status: 'succeed!', data: docs, }); }); };
启动项目时控制台出现报错。
解决办法
- 补全路由路径:Express的
app.get()方法第一个参数必须是路由路径(比如'/api/tours/:id'),修改tour.route.js:app.get('/api/tours/:id', tour_controller.getTourById); - 返回处理函数:handler.js中的
getOne函数没有返回catchAsync包裹的异步函数,导致getTourById为undefined,修改handler.js:exports.getOne = (Model, popOptions) => { return catchAsync(async (req, res, next) => { let query = Model.findById(req.params.id); if (popOptions) { query = query.populate(popOptions); } const docs = await query; if (!docs) { return next( new apiError('No documents found with ID: ' + req.params.id, 404) ); } res.status(200).json({ status: 'succeed!', data: docs, }); }); }; - 规范变量声明:tour_controller.js中的
getTourById缺少声明关键字,添加const避免全局变量污染:const getTourById = handler.getOne(TourModel);
内容的提问来源于stack exchange,提问作者D-Sibu
相关产品推荐
相关产品推荐

