如何使用护照js在POST请求中获取req.user

时间:2017-06-19 00:10:04

标签: javascript node.js express passport.js

从POST请求中获取用户名时遇到问题。 它确实适用于获取请求。

示例:(工作)

app.get('/images', function(req, res){
console.log(req.user)
    if (req.isAuthenticated()){
        res.render('images',{ data: {user: req.user, message: req.flash('loginMessage') }} )
    }
    else {res.redirect('/login')}
});

示例:(作品)

app.post('/login', passport.authenticate('local-login', {
          successRedirect : '/', // redirect to the secure profile section
          failureRedirect : '/login', // redirect back to the signup page if there is an error
          failureFlash : true // allow flash messages
    }),
      function(req, res) {
          if (req.body.remember) {
            req.session.cookie.maxAge = 1000 * 60 * 3;
          } else {
            req.session.cookie.expires = false;
          }
      res.redirect('/');
  });

本地登录策略:(我正在使用mySQL)

passport.use(
    'local-login',
    new LocalStrategy({
        // by default, local strategy uses username and password, we will override with email
        usernameField : 'username',
        passwordField : 'password',
        passReqToCallback : true // allows us to pass back the entire request to the callback
    },
    function(req, username, password, done) { // callback with email and password from our form
        connection.query("SELECT * FROM users WHERE username = ?",[username], function(err, rows){
            if (err)
                return done(err);
            if (!rows.length) {
                return done(null, false, req.flash('loginMessage', 'No user found.')); // req.flash is the way to set flashdata using connect-flash
            }

            // if the user is found but the password is wrong
            if (!bcrypt.compareSync(password, rows[0].password))
                return done(null, false, req.flash('loginMessage', 'Oops! Wrong password.')); // create the loginMessage and save it to session as flashdata

            // all is well, return successful user
            return done(null, rows[0]);
        });
    })
);

但是这个POST请求我没有定义!

app.post('/postAlarms',function(req, res){
    console.log(req.user)
    });

AJAX请求是:

$.ajax({
            url: "http://"+ip+":3000/postAlarms",
            type: 'POST',
            data: {
                arr: ids
            },
            success: function(data){
                console.log(data);
            }
          });

如何获取POST数据到服务器的用户的用户名?

0 个答案:

没有答案