Search code examples
javascriptnode.jsbcrypt

res.redirect is not redirecting anywhere


Like most of my questions I see similar ones but they aren't the same resolutions. My res.redirect simple just does nothing. The page stays the same and absolutely no attempt of a redirect is made.

I have tried placing the res.redirect in other spots but then I get errors. I just want the page to redirect to another after logging in.

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');
      }
   });
});

Server side code:

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 = "";

}

Solution

  • As You finally sent You client-side code let's fix both of sides:

    Idea is to send json payload to server and get json response from server and act depending on status code.

    So server-side part does not return redirect - client-side does redirect itself.

    1) server-side

    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) client-side

    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;
        }
      };
    }