简体   繁体   中英

Express.js - req.query vs req.params

Before you mark this as a duplicate, please understand that I was not able to get the explanations I was looking for from other answers.

If I was making an app that looked for a customer based on a URL id, what is the difference between saying customers/1234 and using req.params and customers?id=1234 and using req.query ? What do the two url data methods do differently?

there is no difference whatsoever from the performance or functionality. is about the standards specifically restful vs non restful urls. usually on restful services the resources identification portion lies on the path and the query or search is used for filtering purposes. this is considered a good practice and it is convention. there is no actual technical reason behind it other than being easier to read and identify. you can learn more about this in places like

https://restfulapi.net/resource-naming/

http://www.vinaysahni.com/best-practices-for-a-pragmatic-restful-api

https://hackernoon.com/restful-api-designing-guidelines-the-best-practices-60e1d954e7c9

Among others. It is all about what you are trying to build and how close to the standards do you want to stay

According to the express docs it looks like the differences between req.query and req.params are just as you mentioned, in that they are a different way to achieve a similar end result. Which you choose is really just a matter of your personal preference for how you want to pass data to Express.

It's the same, but customers/1234 is prettier than customers?id=1234 in URLs.

It depends on what you prefer , but if you compare websites, you'll see that many of them use the first syntax. Look at Stackoverflow for example.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM