gpt4 book ai didi

node.js - 认证成功后获取输入的数据

转载 作者:太空宇宙 更新时间:2023-11-04 01:06:49 25 4
gpt4 key购买 nike

我正在使用 Express NodeJs、Passport、connect-flash、mongoose

我的问题是:我无法理解如何在下一个呈现的页面中检索用户名、密码。

请有人建议我如何实现这一目标..

app.js

var http = require('http');
var express = require('express'),
passport = require('passport')
, LocalStrategy = require('passport-local').Strategy,
flash = require('connect-flash'),
User = require('./routes/userdao.js');


passport.use(new LocalStrategy(
function(username, password, done) {
User.findOne({ uname: username ,pwd:password}, function(err, user) {
if (err) { return done(err); }
if (!user) {
return done(null, false, { message: 'Incorrect username.' });
}
return done(null, user);
});
}
));


passport.serializeUser(function(user, done) {
done(null, user._id);
});

passport.deserializeUser(function(id, done) {
User.findById(id, function(err, user) {
done(err, user);
});
});


var app = express();


app.configure(function(){
app.use(express.logger('dev')); /* 'default', 'short', 'tiny', 'dev' */
app.use(express.cookieParser());
app.use(express.bodyParser());
app.use(express.session({ secret: 'mysecret' }));
app.use(flash());
app.use(passport.initialize());
app.use(passport.session());
app.engine('.html', require('ejs').__express);
app.set('view engine', 'html');
app.set('views', __dirname + '/views');
app.use(app.router);
// app.use(express.errorHandler());

}).listen(3000);

console.log('Listening on port 3000...');
app.get('/',function(req,res){
/* req.flash('info', 'Flash is back!')
res.redirect('/success');*/
res.render('home.ejs');
});

app.get('/login',function(req,res){
res.render('login.ejs');
});

app.get('/success',function(req,res){
res.render('success.ejs',{ uname : req.user.username });
});

app.post('/login',
passport.authenticate('local', { successRedirect: '/success', failureRedirect: '/login',
failureFlash: true }));

成功.ejs

<%= uname %> // I WANT TO RETREIVE USERNAME HERE WHICH WAS ENTERED IN LOGIN PAGE..

最佳答案

当您的 passport.deserializeUser 返回用户数据时,passport 将用它填充 req.user 对象。您需要将此对象作为路由处理程序中 res.render 方法的第二个参数传递给模板:

app.js

(...)
app.get('/success', function(req, res, next){
res.render('user', { user: req.user })
});

成功.ejs

<%= user.uname %>

关于node.js - 认证成功后获取输入的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22214665/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com