You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 15:01:05