Node.js:带有多个查询参数的 Express app.get

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19020012/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 15:44:37  来源:igfitidea点击:

Node.js : Express app.get with multiple query parameters

node.jsexpressgetquery-string

提问by tldr

I want to query the yelp api, and have the following route:

我想查询yelp api,有如下路由:

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

When I make a GET request to

当我向

http://localhost:3000/yelp?term=food&location=austin,

http://localhost:3000/yelp?term=food&location=austin,

I get the error

我收到错误

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

What am I doing wrong?

我究竟做错了什么?

回答by luto

Have you tried calling it like this?

你试过这样称呼它吗?

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

The URL you need to call usually looks pretty much like the route, you could also change it to:

您需要调用的 URL 通常看起来很像路由,您也可以将其更改为:

/yelp/:location/:term

To make it a little prettier:

为了让它更漂亮一点:

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

回答by user568109

In the requested url http://localhost:3000/yelp?term=food&location=austin

在请求的网址中 http://localhost:3000/yelp?term=food&location=austin

  • base url/address is localhost:3000
  • route used for matching is /yelp
  • querystring url-encoded data is ?term=food&location=austini.e. data is everything after ?
  • 基本网址/地址是 localhost:3000
  • 用于匹配的路由是 /yelp
  • querystring url-encoded data is ?term=food&location=austinie data is all after ?

Query strings are not considered when peforming these matches, for example "GET /" would match the following route, as would "GET /?name=tobi".

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

So you should either :

所以你应该:

  • use app.get("/yelp") and extract the term and location from req.query like req.query.term
  • use app.get("/yelp/term/:term/location/:location") but modify the url accordingly as luto described.
  • 使用 app.get("/yelp") 并从 req.query 中提取术语和位置,如 req.query.term
  • 使用 app.get("/yelp/term/:term/location/:location") 但按照 luto 的描述相应地修改 url。

回答by Akshat Jiwan Sharma

I want to add to @luto's answer. There is no need to define query string parameters in the route. For instance the route /awill handle the request for /a?q=value.

我想添加到@luto 的答案中。不需要在路由中定义查询字符串参数。例如,路由/a将处理对 的请求/a?q=value

The url parameters is a shortcut to define all the matches for a pattern of route so the route /a/:bwill match

url 参数是定义路由模式的所有匹配项的快捷方式,以便路由/a/:b匹配

  1. /a/b
  2. /a/c
  3. /a/anything
  1. /a/b
  2. /a/c
  3. /a/anything

it wont match

它不会匹配

/a/b/somethingor /a

/a/b/something或者 /a