res.redirect不在任何地方重定向

时间:2019-02-03 23:41:30

标签: javascript node.js bcrypt

就像我的大多数问题一样,我也看到类似的问题,但是它们的解决方法不同。我的res.redirect简单什么也没做。该页面保持不变,并且绝对不会尝试进行重定向。

我尝试将res.redirect放置在其他位置,但随后出现错误。我只希望页面登录后重定向到另一个页面。

app.post('/login', function (req, res) {
  var usernameCollection = mongoDBDatabase.collection('accounts');
  var username = req.body.username;
  var enteredPassword = req.body.password;

  usernameCollection.findOne({
    $or:[
          { username: username}
        ]
    }).then(function(user){
      if (user) {
        console.log('That username was found in the database');
        bcrypt.compare(enteredPassword, user.password.substr(1), function(err, result){
          if(result == true){
              console.log('Password matches!');
              console.log('logged in as ' + username);
              usercurrentlyloggedin = username;
              res.redirect('/username');
          }
          else{
            console.log('Password did not match');
             res.redirect('/');
          }
        });
      }
      else{
        console.log('The username ' + username + ' was NOT found in     the database');
      }
   });
});

服务器端代码:

function login(){
  console.log("login: " + usernameField.value, pwField.value);
  console.log('login button clicked');

  var postRequest = new XMLHttpRequest();
  var requestURL = '/login';
  postRequest.open('POST', requestURL);

  var requestBody = JSON.stringify({
    personId: usernameField.value,
    username: usernameField.value,
    password: pwField.value
  });

  postRequest.setRequestHeader('Content-Type', 'application/json');
  postRequest.send(requestBody);

  usernameField.value= "";
  pwField.value = "";

}

1 个答案:

答案 0 :(得分:1)

当您最终发送给您客户端代码时,让我们修复双方:

想法是将json负载发送到服务器,并从服务器获取json响应,并根据状态代码采取行动。

因此服务器端部分不会返回重定向-客户端会自行重定向。

1)服务器端

app.post('/login', async (req, res) => {
  try {
    const collection = mongoDBDatabase.collection('accounts');
    const {username, password} = req.body;

    const user = await collection.findOne({username});
    if (
      user &&
      await bcrypt.compare(password, user.password.substr(1))
    ) {
      res.status(200).send({});
      return;
    }

    res.status(403).send({message: 'Access denied'});
  }
  catch (error) {
    console.log(error);
    res.status(500).send({error: error.message});
  }
});

2)客户端

function login(){
  console.log('login:',  usernameField.value, pwField.value);
  console.log('login button clicked');

  // request initialization
  var request = new XMLHttpRequest();
  request.setRequestHeader('Content-Type', 'application/json');
  request.responseType = 'json';
  request.open('POST', '/login');
  request.send(
    JSON.stringify({
      username: usernameField.value,
      password: pwField.value
    })
  );

  // request handling
  request.onload = function(e) {
    // success, redirecting user
    if (this.status == 200) {
      window.location.href = '/username';  
      return;
    }

    // got 403 from server, credentials are invalid
    if (this.status == 403) {
      alert('Username and/or password invalid.');
      return;
    }

    // system error raise
    if (this.status == 500) {
      alert('System error. Contact support.');
      return;
    }
  };
}