在AJAX登录的Node.js页面重定向?在重定向后使用函数调用

Node.js Page Redirect on AJAX login? With a function call after redirect?

本文关键字:重定向 函数调用 登录 AJAX Node js      更新时间:2023-09-26

'/stories'页面是特定于用户的,需要有效的登录凭据。

验证在重定向之前由节点、服务器端和适当的日志进行计算,但不会重定向到故事页面。

这似乎是因为"您不能在AJAX之后进行重定向。"你需要自己在Javascript中完成它",但是这个问题的第一个答案中的代码似乎有些不完整…对于成功调用…

另外,如何在重定向成功后调用后续函数(refreshStories) ?

这是AJAX:

if (loginUsername.length != 0) {
  console.log('there is a login: ' + loginUsername);
    // make an ajax call
    $.ajax({
    dataType: 'json',
    data: AjaxLoginData,
    type: 'post',
      url:"http://localhost:4200/api/v1/users",
      success: (data, textStatus, jqXHR) ->
          if typeof data.redirect == 'string'
              window.location = data.redirect
      success: refreshStories,
      error: foundError
    });

Node.js + Express4

router.route('/users')
    // log in a user (accessed at POST http://localhost:4200/api/v1/users)
    .post(function(req, res) {
      var username = req.body.loginUsername;
      var password = req.body.loginPassword;
      authenticateUser(username, password, function(err, user){
      console.log('authenticate user..');
        if (user) {
          console.log('yes user');
          // subsequent requests will know the user is logged in
          req.session.username = user.username;
          console.log('set session username to: ' + req.session.username);
          // res.redirect('/stories');
                res.send({redirect: '/stories'});
          console.log('user logged in .. redirect to stories');
        } else {
          console.log('user authentication badCredentials error..');
          res.render('index', {badCredentials: true});
        }
      });
    });

试试这个

if (loginUsername.length != 0) {
  console.log('there is a login: ' + loginUsername);
    // make an ajax call
    $.ajax({
    dataType: 'json',
    data: AjaxLoginData,
    type: 'post',
      url:"http://localhost:4200/api/v1/users",
      success: (data, textStatus, jqXHR) ->
          if (typeof data.redirect == 'string')
              window.location.replace(window.location.protocol + "//" + window.location.host + data.redirect);
      error: foundError
    });

window.location.replace(…)最能模拟HTTP重定向如何在JavaScript/jQuery重定向到另一个网页?

对于你的'refreshStories'的东西,你应该刷新故事当你去'/Stories'