简体   繁体   中英

Node.js same uri but different parameters

I'm doing a simple library API with Node.js and express. To fetch a specific book with ISBN or books within a specific genre, I have the following functions:

/api/books/isbn

router.get('/:isbn', function (req, res) 
{
  var isbn = req.params.isbn
})

/api/books/query

router.get('/:genre', function (req, res) 
{
  var genre = req.params.isbn
})

So first of all, this will not work because it will only go to the first function regardless of what the input is. Another thing I tried and that worked, was to make only one function that extracts the query parameters:

router.get('/', function (req, res) 
{
  var isbn = req.query.isbn
  var genre = req.query.genre
})

Using this approach I could get the different values by doing calls like /api/books?genre=Adventure or /api/books?isbn=1231230912

But I feel it would make more sense to do it the first way, ie /api/books/adventure or /api/books/isbn .

So, which way is the 'right' way? And if it's the first one, how can I design the functions so that they can extract the right values?

I think the second approach you tried should also be ok.

However, if you asked me to do this. I will create below apis:

  1. /api/books/genre/Adventure
  2. /api/books/isbn/1231230912

This helps to have clear distinctions between the apis and makes them maintainable and readable for future.

To save the time of writing 2 route handlers, you can write only one route handler function and pass either genre or isbn as parameter.

Try using one route, and by trying to parse the parameter to a number you can check if it's an isbn or genre.

If NaN then genre else isbn

You could do like so :

// /api/

router.get('/isbn/:isbn', function (req, res) 
{
  var isbn = req.params.isbn
})

// /api/books/query

router.get('/genre/:genre', function (req, res) 
{
  var genre = req.params.genre
})

This will work and this is the most used format.

And if you wan't to have only one uri then do like so :

// /api/books/isbn

router.get('/', function (req, res) 
{
    var isbn = req.query.isbn
    var genre = req.query.genre
    if (isbn)
        res.redirect('/isbn/' + isbn);
    else if (genre)
        res.redirect('/genre/' + genre);
})

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