来自AJAX调用的res.redirect

Far*_*rid 4 javascript ajax jquery express

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

客户:

$(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'
    }
})
Run Code Online (Sandbox Code Playgroud)

服务器:

/* 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."})
            }
        })
    })
})
Run Code Online (Sandbox Code Playgroud)

main.hbs登录成功后我无法渲染.我的注释代码有效,但我正在尝试重定向服务器端而不是客户端,因为我被告知它对安全性更好.

Ben*_*ong 5

我不认为你想做的事情是可能的。AJAX 请求只是为了来回传递数据。现在发生的事情是您需要编写客户端行为的脚本。这意味着 AJAX 请求会将 302 和其他数据传递给 JS 上的回调。不能从服务器更改客户端行为。您可以对 AJAX 返回值进行处理。如果是 500,则抛出错误消息,如果是 200,则执行某些操作等。

使服务器重定向工作的唯一方法是通过传统的 HTML 表单提交。


Kes*_*ran 5

您应该知道何时使用hrefreplace功能.

window.location.replace(...) 将是表示HTTP重定向的最佳方式.

原因

与之相比window.location.href,window.location.replace(...)最好在HTTP重定向场景中使用,因为replace()避免将原始页面保留在会话历史记录中,这有助于用户避免陷入永无止境的后退按钮惨败.

摘要

如果要说明单击链接,请使用 location.href

如果要说明HTTP重定向,请使用 location.replace

样品

//  an HTTP redirect
window.location.replace("http://example.com");

//  clicking on a link
window.location.href = "http://example.com";
Run Code Online (Sandbox Code Playgroud)

更新

服务器无法从ajax请求进行重定向.最后,ajax涉及客户端(浏览器).

如果需要,可以通过服务器端调用发送重定向指令,但它将在客户端再次在回调中结束.您可以通过从服务器返回包含要重定向到的URL的对象来执行此操作.然后使用javascript更改文档的位置属性.如下:

服务器端代码

if (result) {
    var token = jwt.encode(user, JWT_SECRET)
    return res.status(200).send({result: 'redirect', url:'/'})
} else {
    return res.status(401).send({error: "Something is wrong."})
}
Run Code Online (Sandbox Code Playgroud)

然后在Client Side Javascript中:

$.ajax({
  type: "put",
  url: '/login',
  data: {
    username: username,
    password: password
  }
  success: function(response) {
    if (response.result == 'redirect') {
      //redirecting to main page from here.
      window.location.replace(response.url);
    }

  }
});
Run Code Online (Sandbox Code Playgroud)

除此之外,您的注释代码是执行此操作的正确方法.就像你提出的一条评论一样,"服务器端重定向是一个ajax请求的deadend,因为该指令不适用于浏览器,而是一些javascript处理程序."