res.redirect from an AJAX call

Viewed 8408

I'm trying to do a redirect after an ajax put request. I plan on using pure JS client side for validation.

Client:

$(document).ready(function() {
    login = () => {
        var username = $("[name='username']").val()
        var password = $("[name='password']").val()
        $.ajax({
            type: "put",
            url: '/login',
            data: {
                username: username,
                password: password
            }
            // success: function(response) {
            //  console.log('Success:')
            //  console.log(response.user)

            //  Cookies.set('username', response.user.username)
            //  Cookies.set('first_name', response.user.first_name)
            //  Cookies.set('last_name', response.user.last_name)
            //  Cookies.set('email', response.user.email)

            //  window.location.href = window.location.origin + '/'
            // },
            // error: function(error) {
            //  console.log("Error:")
            //  console.log(error)
            // }
        })
    }

    logout = () => {
        console.log("Log out clicked.")
        Cookies.remove('username')
        Cookies.remove('first_name')
        Cookies.remove('last_name')
        Cookies.remove('email')
        window.location.href = window.location.origin + '/logout'
    }
})

Server:

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('main')
});

router.put('/login', function(req, res) {
    // Password is not encrypted here
    console.log('req.body')
    console.log(req.body)

    User.findOne({ username: req.body.username }, function(err, user) {
        // Password is encrypted here
        if (err) throw err
        console.log('user')
        console.log(user)

        bcrypt.compare(req.body.password, user.password, function(err, result) {
            if (result) {
                var token = jwt.encode(user, JWT_SECRET)
                // return res.status(200).send({ user: user, token: token })
                return res.redirect('/')
            } else {
                return res.status(401).send({error: "Something is wrong."})
            }
        })
    })
})

I can't get main.hbs to render after a successful login. My commented code works, but I'm trying to do my redirect server side rather than client side because I'm told that it's better for security.

2 Answers
Related