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

Node.js中GET /api/restaurants路由无法处理查询参数格式请求的问题排查

问题:GET路由无法处理查询参数格式请求,返回"Cannot GET /api/restaurants"

我需要实现一个GET /api/restaurants路由,要求接收数值类型的查询参数page、perPage,以及可选的字符串参数borough,示例请求格式是/api/restaurants?page=1&perPage=5&borough=Bronx。这个路由要返回指定页码的Restaurant对象,如果提供了borough参数还要按该字段过滤结果。

我当前写的代码如下:

app.get('/api/restaurants/:page/:perPage/:borough', (req, res) =>{
  console.log("worked")
  console.log(req.params.page)
  console.log(req.params.perPage)
  console.log(req.params.borough)
})

现在遇到的问题是:当用路径参数格式的URL(比如http://localhost:8000/api/restaurants/1/5/Bronx)访问时,路由能正常工作;但用需求要求的查询参数格式URL访问时,就会报错"Cannot GET /api/restaurants"。想请大家帮我看看哪里出错了,非常感谢!


解决方案

嘿,问题很明确——你搞混了路径参数和查询参数的路由定义方式啦!

1. 先修正路由路径

你现在写的/api/restaurants/:page/:perPage/:borough是路径参数的写法,也就是说这些参数是URL路径的一部分。但需求里要求的是查询参数(就是?后面跟着的键值对),所以路由路径应该直接写成/api/restaurants,不需要在路径里加参数占位符:

app.get('/api/restaurants', (req, res) =>{
  // 后续逻辑写在这里
})

2. 正确获取查询参数

在Express中,查询参数是存储在req.query对象里的,而不是req.params(req.params是用来拿路径参数的)。另外要注意,查询参数默认都是字符串类型,所以需要把page和perPage转成数值:

app.get('/api/restaurants', (req, res) =>{
  // 转换并获取参数
  const page = parseInt(req.query.page);
  const perPage = parseInt(req.query.perPage);
  const borough = req.query.borough;

  console.log('页码:', page);
  console.log('每页数量:', perPage);
  console.log('行政区:', borough);

  // 接下来就可以在这里实现数据库查询逻辑了:
  // - 如果有borough参数,就添加过滤条件
  // - 根据page和perPage计算分页的偏移量,返回对应页的数据
})

3. 可选但重要:参数校验

为了避免非法参数(比如page传了字符串、负数)导致后续逻辑出错,建议加个简单的校验:

app.get('/api/restaurants', (req, res) =>{
  const page = parseInt(req.query.page);
  const perPage = parseInt(req.query.perPage);
  const borough = req.query.borough;

  // 校验page和perPage是否为有效正整数
  if (isNaN(page) || page < 1 || isNaN(perPage) || perPage < 1) {
    return res.status(400).json({ error: 'page和perPage必须是大于0的有效数值' });
  }

  // 这里写你的分页+过滤逻辑
})

改完之后,再用http://localhost:8000/api/restaurants?page=1&perPage=5&borough=Bronx访问,就能正常触发这个路由啦!

内容的提问来源于stack exchange,提问作者Ivo Biz

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.28 09:47:34