You need to enable JavaScript to run this app. Node.js+Express开发餐厅API时Postman报Cannot GET错误求助
优惠活动
大模型
产品
解决方案
定价
更多

Node.js+Express开发餐厅API时Postman报Cannot GET错误求助

接口报错排查与修复方案

直接报错原因

你定义的路由规则为:

router.get('/restaurantData/:cityID',restaurantController.getRestaurantData);

该路由强制要求携带cityID路径参数,合法请求路径格式为http://localhost:4005/api/restaurantData/{城市ID}(例如/api/restaurantData/1)。你当前请求的/api/restaurantData未携带路径参数,Express无法匹配到对应路由,因此抛出Cannot GET /api/restaurantData错误。


关联问题修复(路由匹配成功后仍会触发的错误)

1. 路由参数名与Controller取值不匹配

路由定义的参数名是cityID(ID大写),但Controller中读取参数的代码为req.params.city_id(id小写),大小写不一致会导致取不到参数,触发Cannot read properties of undefined (reading 'toString')报错。
修复方案二选一:

  • 修改路由参数为小写:
    router.get('/restaurantData/:city_id',restaurantController.getRestaurantData);
    
  • 或者修改Controller的参数读取逻辑:
    console.log(req.params.cityID.toString())
    

2. Mongoose Schema重复定义字段

Model中重复定义了name字段,后续定义会覆盖前序定义,属于冗余代码,删除重复片段即可:

// 删除以下重复代码
name:{
    type: String,
    required: true
},

3. (可选)CORS配置补全

当前CORS规则仅允许GET、POST方法,后续如需使用其他HTTP方法可按需补充:

res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, PATCH');

验证流程

  1. Postman请求路径补全对应城市ID,例如http://localhost:4005/api/restaurantData/1(其中1需与MongoDB中restaurantData集合存储的city_id值一致)
  2. 确认MongoDB服务已正常启动,且数据库存在匹配的餐厅数据
  3. 检查控制台是否有路由参数取值相关的报错

内容的提问来源于stack exchange,提问作者Prajual Kotian

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.12 18:27:00