【问题标题】:Node.js : Express app.get with multiple query parametersNode.js:使用多个查询参数表达 app.get
【发布时间】:2013-10-01 22:27:49
【问题描述】:

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

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

当我向

发出 GET 请求时

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

我得到了错误

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

我做错了什么?

【问题讨论】:

    标签: node.js express get query-string


    【解决方案1】:

    你试过这样称呼它吗?

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

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

    /yelp/:location/:term
    

    为了让它更漂亮一点:

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

    【讨论】:

      【解决方案2】:

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

      • 基本网址/地址是localhost:3000
      • 用于匹配的路由是/yelp
      • querystring url 编码的数据是?term=food&location=austin,即数据是后面的所有内容?

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

      所以你应该:

      • 使用 app.get("/yelp") 并从 req.query 中提取术语和位置,例如 req.query.term
      • 使用 app.get("/yelp/term/:term/location/:location") 但按照 luto 的描述相应地修改 url。

      【讨论】:

        【解决方案3】:

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

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

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

        不匹配

        /a/b/something/a

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2014-05-08
          • 2011-06-15
          • 1970-01-01
          • 2021-03-07
          • 2012-07-28
          • 2013-03-04
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多