node js express routes /users?limit=20&offset=0

时间:2016-10-15 17:22:10

标签: javascript node.js express

i'm learning node js at the moment at school, but i block on one route that i need to make.

I have a database with some users, with localhost/users i can get all users and print it on the page.

But i block on one route : localhost/users?limit=20&offset=0, this route is like the previous but the limit is 20 users on the page, but when i write this url on my navigator, he just stay on the /users route without considering my params(limit and offset) :/.

Here is my code :

app.get('/users', (req, res, next) => {

console.log('/users')
  db.all('SELECT * FROM users').then((users) =>  {
      res.send(users)
      next()
  })
})


app.get('/users/:userId', (req, res, next) => {
  console.log('aleluya')
  console.log('-> GET /users/:userId (userId : ' + req.params.userId +')')
  var id = req.params.userId;
  db.all('SELECT * from users WHERE rowid = '+ id +'' ).then((users) => {


  res.send(users)
  next()
})
})



app.get('/users?limit=20&offset=0', (req, res, next) => { // prendre l'url
  console.log('/users?limit=20&offset=0') // afficher dans la console
    limit = req.params.limit 
    offset = req.params.offset // mettre 0 dans offset
    console.log(limit, offset)
    db.all('SELECT * FROM users LIMIT '+ limit +' OFFSET '+ offset +'').then((users) =>  {
        res.send(users)
        next()
    })
  })

1 个答案:

答案 0 :(得分:1)

that is because your path is still /users

To access query parameters you have to use:

// console.log(req.query['key'])
//
//     req.query.limit  
//     req.query.offset

So, you may modify your code like this:

app.get('/users', (req, res, next) => {
console.log('/users')
if( req.query.limit ){
    return doQueryUsers(req, res, next);
}
  db.all('SELECT * FROM users').then((users) =>  {
      res.send(users)
      next()
  })
})


app.get('/users/:userId', (req, res, next) => {
  console.log('aleluya')
  console.log('-> GET /users/:userId (userId : ' + req.params.userId +')')
  var id = req.params.userId;
  db.all('SELECT * from users WHERE rowid = '+ id +'' ).then((users) => {


  res.send(users)
  next()
})
})



var doQueryUsers = function(req, res, next) { // prendre l'url
  console.log('/users?limit=20&offset=0') // afficher dans la console
    limit = req.query.limit 
    offset = req.query.offset // mettre 0 dans offset
    console.log(limit, offset)
    db.all('SELECT * FROM users LIMIT '+ limit +' OFFSET '+ offset +'').then((users) =>  {
        res.send(users)
        next()
    })
  }