来自AJAX调用的res.redirect [英] res.redirect from an AJAX call

查看:123
本文介绍了来自AJAX调用的res.redirect的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在ajax put请求之后进行重定向.我计划使用纯JS客户端进行验证.

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

客户:

$(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'
    }
})

服务器:

/* 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."})
            }
        })
    })
})

成功登录后,我无法获得main.hbs进行渲染.我注释过的代码有效,但是我试图做重定向服务器而不是客户端,因为有人告诉我这样做对安全性更好.

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.

推荐答案

我认为您想做的事不可行. AJAX请求仅用于来回传递数据.现在发生的事情是您需要编写客户端行为脚本.这意味着AJAX请求将传递302以及随之而来的其他数据传递给JS上的回调.不能从服务器更改客户端行为.取决于您如何使用AJAX返回的值.如果是500,则抛出错误消息,然后执行200,以此类推.

I don't think what you want to do is possible. An AJAX request is meant just to pass data back and forth. What happens now is that you need to script client side behavior on your end. This means the AJAX request will pass a 302 and other data that comes along for the ride to the callback on JS. No client side behavior can be altered from the server. It is up to you to do something with the AJAX returned values. If 500, throw an error message, 200 do something etc.

使服务器重定向正常工作的唯一方法是传统的HTML表单提交.

The only way you can get a server redirect to work is by traditional HTML form submission.

这篇关于来自AJAX调用的res.redirect的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆