Node.js:使用多个查询参数的Express app.get

12

我想查询 Yelp API,并拥有以下路由:

app.get("/yelp/term/:term/location/:location", yelp.listPlaces)

当我向 http://localhost:3000/yelp?term=food&location=austin 发送GET请求时,我收到了以下错误:

Cannot GET /yelp?term=food&location=austin

我做错了什么?

4个回答

14

你尝试过像这样调用它吗?

http://localhost:30000/yelp/term/food/location/austin

你需要调用的URL通常与路由非常相似,你也可以将其更改为:

/yelp/:location/:term

为了让它更美观一些:

http://localhost:30000/yelp/austin/food

12
在请求的URL中 http://localhost:3000/yelp?term=food&location=austin
  • 基础 URL/地址是 localhost:3000
  • 用于匹配的路由是 /yelp
  • 查询字符串 URL 编码数据为 ?term=food&location=austin,即数据是 ? 之后的所有内容

执行这些匹配时不考虑查询字符串,例如 "GET /" 将匹配以下路由,"GET /?name=tobi" 也将匹配。

因此,您应该:

  • 使用 app.get("/yelp") 并从 req.query 中提取 term 和 location,例如 req.query.term
  • 使用 app.get("/yelp/term/:term/location/:location") ,但根据 luto 的描述修改 URL。

4
我想补充一下@luto的答案。在路由中没有必要定义查询字符串参数。例如,路由/a将处理/a?q=value的请求。
URL参数是定义路由模式的所有匹配项的快捷方式,因此路由/a/:b将匹配:
  1. /a/b
  2. /a/c
  3. /a/anything
它不会匹配/a/b/something/a

0

Express 4.18.1 更新:

使用 app.get("/yelp/term/:term/location/:location"),你的查询字符串可以是 yelp/term/food/location/austin

因此,你的请求 URL 将会是这样的:

http://localhost:3000/yelp/term/food/location/austin

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接