Javascript I';我不知道是应该使用URL路径参数还是查询参数在后端进行过滤?

Javascript I';我不知道是应该使用URL路径参数还是查询参数在后端进行过滤?,javascript,node.js,express,Javascript,Node.js,Express,假设我想从某个汽车品牌获得所有车型。我知道我可以通过使用URL路径参数或以下查询参数来实现: router.get('/modelsByBrand', modelController.getModelsByBrand); https://example.com/modelsByBrand?brandId=1 https://example.com/modelsByBrand/1 router.get('/models', modelController.getModels); 然后像这样

假设我想从某个汽车品牌获得所有车型。我知道我可以通过使用URL路径参数或以下查询参数来实现:

router.get('/modelsByBrand', modelController.getModelsByBrand);
https://example.com/modelsByBrand?brandId=1
https://example.com/modelsByBrand/1
router.get('/models', modelController.getModels);
然后像这样发出GET请求:

router.get('/modelsByBrand', modelController.getModelsByBrand);
https://example.com/modelsByBrand?brandId=1
https://example.com/modelsByBrand/1
router.get('/models', modelController.getModels);
在控制器中,使用以下命令获取品牌ID:

let brand = req.query.brandId
let brand = req.params.brandId

然后像这样发出GET请求:

router.get('/modelsByBrand', modelController.getModelsByBrand);
https://example.com/modelsByBrand?brandId=1
https://example.com/modelsByBrand/1
router.get('/models', modelController.getModels);
在控制器中,使用以下命令获取品牌ID:

let brand = req.query.brandId
let brand = req.params.brandId

但我只是不确定应该使用哪一种,因为这两种方法似乎几乎相同。是否存在我需要使用其中一个而不是另一个的情况,或者只是偏好?我可以用这两种方法中的任何一种吗?

如果您有几个参数要过滤和获取模型,那么它应该如下所示:

router.get('/modelsByBrand', modelController.getModelsByBrand);
https://example.com/modelsByBrand?brandId=1
https://example.com/modelsByBrand/1
router.get('/models', modelController.getModels);
请求应该是这样的

https://example.com/models // get all models
https://example.com/models?brandId=1 // get all models with brandId = 1
https://example.com/models?name=Model1 // get all models where a name contains "Model1"
https://example.com/models?brandId=1&name=Model1 // get all models with brandId = 1
and a name contains "Model1"
最后通过id得到一个模型

router.get('/models/:id', modelController.getModel);
还有一个请求

https://example.com/models/1 // get a model with id=1

我想这看起来更像RESTful路由。

如果您有几个参数要过滤和获取模型,那么它应该是这样的:

router.get('/modelsByBrand', modelController.getModelsByBrand);
https://example.com/modelsByBrand?brandId=1
https://example.com/modelsByBrand/1
router.get('/models', modelController.getModels);
请求应该是这样的

https://example.com/models // get all models
https://example.com/models?brandId=1 // get all models with brandId = 1
https://example.com/models?name=Model1 // get all models where a name contains "Model1"
https://example.com/models?brandId=1&name=Model1 // get all models with brandId = 1
and a name contains "Model1"
最后通过id得到一个模型

router.get('/models/:id', modelController.getModel);
还有一个请求

https://example.com/models/1 // get a model with id=1

我想这更像是RESTful路线。

两者都可以。我的经验法则是,我使用路径指定我想要的资源,使用查询参数指定修饰符,特别是如果可能有许多不同的修饰符。因此,如果
brandId
只是可用于同一请求的众多修饰符之一,那么我“d将其设置为查询参数,以便可以有多个修饰符。但是,如果它本身是主要的资源标识符,那么我会将它放在路径中。两者都可以工作。我的经验法则是,我使用路径指定我想要的资源,使用查询参数指定修饰符,特别是如果可能有许多不同的修饰符。因此,如果
brandId
只是可以在同一请求上使用的众多修饰符之一,那么我会将其设置为查询参数,这样您就可以有多个修饰符。但是,如果它本身是主资源标识符,那么我会将其放在路径中。