Creating similar routes with different parameters in Nodejs

I did a google search but I couldn't find what I really need. I need to request an API that has the same route but with different parameters.

Example:

router.get ('/ items /: query, function () {})

In this case, I would search for all elements

router.get ('/ items /: id, function () {})

Here I would look for a specific element

+3


source to share


2 answers


At the heart of your problem is that you are trying to list two different resources in the same place. If you design your API to follow calm principles, you can see why this is not a wise choice. Here are two good starting points:

https://en.wikipedia.org/wiki/Representational_state_transfer

http://www.restapitutorial.com/lessons/whatisrest.html

In the restful api, the root resource represents a collection of items:

/api/items

      



... and when you provide an id indicating that you only need one element:

/api/items/abc123

      

If you really want to accomplish what you asked in your question, you need to add a url parameter like / items / query? query = true or / items / abc 123? detail = true, but that would be confused with 99% of web developers who ever look at your code.

Also I'm not sure if you really understood this, but when you pass a variable called "query" to the server, which appears to indicate that you are going to send a SQL query (or similar data definition language) from client to server. This is a dangerous practice for several reasons - it's best to leave all this type of code on your server.

Edit: if you really absolutely need to do this, then maybe there is a query parameter that says: collection = true. This at least would be understood by other developers who may have to maintain the code in the future. Also make sure you add comments to explain why you weren't able to implement the vacation so as not to leave a bad reputation behind you :)

+1


source


The problem is that without additional pattern matching, there is no way Express can differentiate /items/:query

and /items/:id

, they are the same route pattern, only with different aliases for the parameter.



Depending on how you plan to structure your request, you might consider using a route /items

and then using query string parameters or having a separate endpoint /items/search/:query

.

0


source







All Articles