Emibrown
Emibrown

Reputation: 187

express js URL cleanup

I create a rout that get user full details from the DATABASE(mongoDB).

Router

router.get('/user/:userid/:name', getUrl, function(req, res, next) {
  User.findOne({_id: req.params.userid})
  .exec(function(err, user) {
     if (err) { return next(err); }
     if (!user) { return next(404); }
     res.render('........');
 });
});

for instance i can access this router with this URL:

http://127.0.0.1/user/6465667/username 

but what i realy want is this

http://127.0.0.1/user/username 

Is there a way of hiding the user ID in the URL

Upvotes: 0

Views: 151

Answers (1)

Maertz
Maertz

Reputation: 4952

Simply remove :userid from your route and use the name to lookup your database. Ensure your username is unique otherwise you might receive the wrong user details.

router.get('/user/:name', getUrl, function(req, res, next) {
  User.findOne({name: req.params.name})
  .exec(function(err, user) {
     if (err) { return next(err); }
     if (!user) { return next(404); }
     res.render('........');
 });
});

Upvotes: 3

Related Questions