0

I have a router like this

app.get('/users/:id',  (req, resp) => {
var id = req.params.id;
if (id) {
    Users.findById(id, (error, record) => {
        if (error) resp.send(error);
        resp.send(record);
        resp.end();
    });
} else {
    // return all users
    Users.find({}, (error, recordset) => {
        if (error) resp.send(error);
        resp.send(recordset);
        resp.end();
    });
}    
});

path /users/164564 is working fine but path /users is not hit the route and returning error message like blow

Cannot GET /users

I can create two routes like app.get('/users',()=>{}); for path /users and app.get('/users/:id',()=>{}); for path /users/164564

Is it possible to maintain id as optional parameter? if no value for id param then return all records.

sridharnetha
  • 2,104
  • 8
  • 35
  • 69

1 Answers1

3

Try this

app.get('/users/:id?',  (req, resp) => {...  // question mark was missing.

instead of

app.get('/users/:id',  (req, resp) => {...

this might help you out.. Thanks

Vikrant Kashyap
  • 6,398
  • 3
  • 32
  • 52
Hang Tu
  • 41
  • 2