事情很有效,但由于某种原因,我无法将user_id输入到URL中,我得到的只是文字“:user_id”,如下所示:
这是my users.js路由文件中的代码
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);
};
这是我的main.js文件中的代码:
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);
答案 0 :(得分:1)
exports.routeUserToTheirHome = function(req, res, next) {
req.user.user_id = req.params.user_id;
res.json(req.user);
};
答案 1 :(得分:0)
我弄清楚问题是什么,就是我有这个:
app.post('/login', passport.authenticate('local', {
successRedirect : 'users/:user_id/home',
failureRedirect : '/login',
failureFlash : true
}), function(req, res, next) {
next();
});
事实上,我需要这个:
app.post('/login', passport.authenticate('local', {
successRedirect : 'users/' + '5464370621a2569c18880876' +'/home',
failureRedirect : '/login',
failureFlash : true
}), function(req, res, next) {
next();
});
显然,我不知道自己在做什么。现在的问题是,我从哪里获取user_id,而不是硬编码?
这是解决方案:
app.post('/login', passport.authenticate('local', {
failureRedirect : '/login',
failureFlash : true
}), function(req, res, next) {
res.redirect('users/' + req.user._id +'/home');
next();
});