在Adonisjs中路由可选参数

时间:2019-10-14 06:33:07

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

尝试在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的结果只是。那我的路线怎么了?

2 个答案:

答案 0 :(得分:0)

在创建路线时,此路线如下

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或通过此打印时获得

答案 1 :(得分:0)

有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
}