0

After a user does something on a page, I use ajax to send some data to my Node.js Express server. That server then does this:

router.post('/', function(req, res){
//user authentication then, inside that callback
  res.redirect('/dashboard');
}

dashboard.js then does this:

router.get('/', function(req, res, next) {
    console.log("dashboard"); //<--This code is running
    res.render('index',{title:"You are logged in"});
}

Now the front end is doing this:

function httpGetAsync(theUrl, callback){
        let user = document.getElementById('username').value;
        let pass = document.getElementById('password').value;
        let data = {
            "username": user,
            "password": pass
        }
        var xmlHttp = new XMLHttpRequest();
        xmlHttp.onreadystatechange = function() {
            if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
                callback(xmlHttp.responseText);
        }
        xmlHttp.open("POST", theUrl, true); // true for asynchronous
        xmlHttp.setRequestHeader("Content-Type", "application/json; charset=utf-8");
        var dataAsJson = JSON.stringify(data);
        xmlHttp.send(dataAsJson);
    }

Instead of seeing my nice "You are logged in" page, index.html logs to my browser's console. This is obviously because my onclick listener does this:

onclick='httpGetAsync("/createUser", console.log)'

Instead of console.log (which is obviously the wrong thing here), what should I be calling?

How do I get this res.render('index',{title:"You are logged in"}) in dashboard.js to actually render?

This is a lot like ExpressJS : res.redirect() not working as expected?, but that question does not include the portion that includes their front end code which is where I think the problem lies. And the last comment there reads: "No, never figured it out. I ended up building my app differently, with the login part in a modal, instead of another page... Very frustrating".

Community
  • 1
  • 1
Glen Pierce
  • 3,247
  • 3
  • 28
  • 44

1 Answers1

1

As XHR are meant to send and revive response you are receiving html page as response with status 301 or 302, the possible solution is to send the redirect url as response instead

router.post('/', function(req, res){
  //user authentication then, inside that callback
  res.send('/dashboard');
}

and on receiving this response you can redirect to response url on callback

function redirect(res){
  window.location = res;
}

onclick='httpGetAsync("/createUser", redirect)'

Basilin Joe
  • 552
  • 9
  • 22