Peter Dowdy
Peter Dowdy

Reputation: 58

Redirects aren't working in ExpressJS

I'm trying to redirect on successful registration. I've knocked together this basic code to test out the principle:

app.post('/register', function(req, res, next) {
User.findOne({ username: req.body.username }, function (err, user) {
    if (err) { return done(err); }
    if (user) {
        res.send(400);
    } else {
        var newUser = new User({ username: req.body.username, password: passwordHash.generate(req.body.password)});
        newUser.save();
        req.logIn(newUser, function(err) {
            if (err) return next(err);
            return res.redirect('/my-events');
        })
    }
});
});

However, when this triggers, my browser sees a 302, followed by a successful GET of the page that the /my-events endpoint serves up...but no redirect.

What's wrong? Using res.redirect works when the browser is loading an endpoint, it just doesn't seem to work as the result of a $.post.

Upvotes: 1

Views: 253

Answers (1)

Akshat Jiwan Sharma
Akshat Jiwan Sharma

Reputation: 16000

You mentioned that you are using $.post for sending the data. If that is the case then server won't be able to redirect to the actual page. What you need to do is redirect the page manually yourself in the call back function of the post function like so.

 $.post('your endpoint',function(){

    window.location = 'page to redirect to';

 });

This should do it.

Upvotes: 1

Related Questions