【问题标题】:Routing optional parameters in AdonisjsAdonisjs 中的路由可选参数
【发布时间】:2019-10-14 20:08:23
【问题描述】:

尝试在adonisjs 中使用可选参数进行路由时遇到问题。当我写不同的端点时,参数的结果也不同

这是我的路由器代码:

Route.post('product/:id_product?', 'ProductController.addProduct')

如果我在邮递员中向此端点发送参数

http://localhost:3333/shoping/product   //the result of parameter is null
or
http://localhost:3333/shoping/product/1    //the result of parameter is 1

可以在console.log 中读取该参数,但如果我尝试运行此端点:

http://localhost:3333/shoping/product    //the result of parameter is null
or
http://localhost:3333/shoping/product?id_product=1    //the result of parameter also null

console.log 的结果只是 null。那么我的路线有什么问题?

【问题讨论】:

    标签: node.js parameters routes postman adonis.js


    【解决方案1】:

    当你创建一个路由这个路由路径像这样

    http://localhost:3333/shoping/product/1
    

    当你像这样在控制器中获得这个 id_product 时

    console.log(params.id_product) 所以可以得到 1 或者当你使用这个路径传递路径时

    http://localhost:3333/shoping/product?id_product=1 
    
    

    这没有给你任何参数,因为在这种情况下 id_product 是一个查询参数,如果你在这个路径中得到 id_product 那么你会得到这样的

          const queryData = request.get();
          console.log(queryData.id_product)
    

    所以得到 1 或者当你通过这个 print

    【讨论】:

    • 如果我在路由中创建:id_product? 怎么样?实际上这个可选路由将返回http://localhost:3333/shoping/product?id_product=1 或http://localhost:3333/shoping/product/1?我很困惑,因为我仍然可以使用这两个端点..
    • 如果你创建这条路线:id_product?然后你得到params.id_product并且你得到?查询参数然后使用request.get() http://localhost:3333/shoping/product/1这是你:id_product的端点
    【解决方案2】:

    有两个区别:

    1. Request body

    网址示例:

    http://localhost:3333/shoping/product?id_product=1
    http://localhost:3333/shoping/product?id_product=1&name=test
    

    路由示例:shoping/product

    控制器集成:

    test ({request}) {
     const product = request.only(['id_product', 'name'])
    
     console.info(product.id_product) //output 1
    }
    
    1. Route parameters

    网址示例:

    http://localhost:3333/shoping/product/1
    

    路由示例:shoping/product/:id_product?

    控制器集成:

    test ({params}) {
     const id_product = params.id_product
    
     console.info(id_product ) //output 1
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-22
      • 2012-03-24
      • 2015-02-05
      相关资源
      最近更新 更多