假设我想从某个汽车品牌获得所有车型。我知道我可以通过使用URL路径参数或像这样的查询参数来完成:
router.get('/modelsByBrand', modelController.getModelsByBrand);
然后发出这样的GET请求:
https://example.com/modelsByBrand?brandId=1
在控制器中,使用以下方法获取品牌的ID:
let brand = req.query.brandId
或
router.get('/modelsByBrand/:brandId', modelController.getModelsByBrand);
然后发出这样的GET请求:
https://example.com/modelsByBrand/1
在控制器中,使用以下方法获取品牌的ID:
let brand = req.params.brandId
但我只是不确定我应该使用哪种方法,因为这两种方法似乎几乎完全相同。是否存在我需要使用其中一个而不是另一个的情况,或者这只是偏好?我可以用任何一种方法来做任何事情吗?
如果你有几个参数要过滤和获取模型,那么它应该是这样的:
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路由。