Alexander Mills
Alexander Mills

Reputation: 99960

node.js - parameterized routes with Express

Things are sort of working but, for some reason, I can't get the user_id into the URL, all I get is a literal ":user_id" like so:

enter image description here

here is the code in the my users.js route file

var main = require('../main');

exports.getAllUsers = function(req, res) {

    var db = main.db();

    db.collection('users').find().toArray(function(err, items) {
        res.json(items);
    });

};

exports.routeUserToTheirHome = function(req, res, next) {
      res.json(req.user);
};

and here is the code in my main.js file:

app.param('user_id', function(req, res, next, user_id) {
    // typically we might sanity check that user_id is of the right format
    User.find(user_id, function(err, user) {
        if (err) {
            return next(err);
        }
        if (!user) {
            return new Error("no user matched");
        }
        req.user = user;
        next();
    });
});

app.use('/users/:user_id/home', users.routeUserToTheirHome);

Upvotes: 0

Views: 176

Answers (2)

Alexander Mills
Alexander Mills

Reputation: 99960

I figured out what the problem was, it was that I had this:

app.post('/login', passport.authenticate('local', {
    successRedirect : 'users/:user_id/home',
    failureRedirect : '/login',
    failureFlash : true
}), function(req, res, next) {
    next();
});

when in fact, I needed this:

app.post('/login', passport.authenticate('local', {
    successRedirect : 'users/' + '5464370621a2569c18880876' +'/home',
    failureRedirect : '/login',
    failureFlash : true
}), function(req, res, next) {
    next();
});

clearly I don't know what I am doing. The question now is, where do I get the user_id from, instead of hardcoding it?

here is the solution:

app.post('/login', passport.authenticate('local', {
    failureRedirect : '/login',
    failureFlash : true
}), function(req, res, next) {
    res.redirect('users/' + req.user._id +'/home');
    next();
});

Upvotes: 0

takinola
takinola

Reputation: 1763

exports.routeUserToTheirHome = function(req, res, next) {
    req.user.user_id = req.params.user_id;
    res.json(req.user);
};

Upvotes: 1

Related Questions