简体   繁体   中英

req.login is not logging the user

What I am trying to do is use ajax to send a post request to the server, and make sure that post request does not refresh the page (using e.preventDefault). On the server I want to check if the username or email is taken and if it is not taken, then automatically log the user in and then refresh the page. The issue is when I call req.login and submit the data to be logged in it doesn't seem to be working but the page still refreshes. Any ideas?

app.post('/signup', function (req, res) {
var userDetails = User({
    username: req.body.username,
    email: req.body.email,
    password: bcrypt.hashSync(req.body.password1, bcrypt.genSaltSync(10))
});

User.findOne({
    $or: [{
        'username': req.body.username
    }, {
            'email': req.body.email
        }]
}, function (err, user) {
    if (user) {
        if (allClients.indexOf(req.body.socket)) {
            if (user.username === req.body.username) {
                io.to(req.body.socket).emit('userInfo', 'That username is already in use.');
            } else {
            }
            if (user.email === req.body.email) {
                io.to(req.body.socket).emit('userInfo', 'That email is already in use.');
            } else {
            }
        } else {
            console.log('timeout error 822')
        }
    } else {
        req.login(userDetails, function (err) {
            if (!err) {
                userDetails.save(function (err) {
                    if (err) throw err;
                    res.redirect('/');
                });
            } else {
                console.log(err)
            }
        })
    }
    if (err) {
        return done(err);
    }
});
});

Here is where I make the ajax post request. As you can see I am preventing the form submit to refresh the page, but if the form is succesful it will submit.

$("#form1").submit(function(e) {
        e.preventDefault();
        $.ajax({
            type: "POST",
            url: '/signup',
            data: $(this).serialize(),
            success: function(data)
            {
                window.location.reload(true);
            }
        });
 });

I believe your 'already taken' messages are considered success by your API. You can either throw an error on those cases and catch with $.ajax or set a different response and read data on success .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM