cgifox
cgifox

Reputation: 659

Nodejs - Response of POST request is undefined

I'm learning nodejs, and made a simple site to learn to handle POST requests.

Here is my code:

Browser-side:

function sendRequest (params) {
  var xhr = new XMLHttpRequest();
  var url = 'result';
  xhr.open("POST",url,true);

  xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');

  xhr.onreadystatechange = function () {
    console.log('onreadystatechange');
    if(xhr.readyState == 4 && xhr.status == 200){
      console.log('Response text:' + xhr.reponseText);
    }
  }

  xhr.send(params);
}

Server-side:

else if (req.url === '/result') {
    req.on('data', function (data) {
        var params = data.toString().split('&');
        var result = calc(params);
        console.log(result.toString());
        res.writeHead(200,{'Content-Type':'text/plain'});
        res.write('<div>'+result.toString()+'</div>');
        res.end();
        console.log('Response over');
    });
  }

When i run this,xhr.responseText is undefined, and i'm having trouble understanding where the error is.

Based on the log, node gets the request, the result is correct,and xhr.onreadystatechange also runs(but xhr.responseText is undefined).

Upvotes: 0

Views: 601

Answers (1)

Mukesh Sharma
Mukesh Sharma

Reputation: 9022

There is typing error in your browser side code. You misspelled responseText.

console.log('Response text:' + xhr.responseText);

Upvotes: 1

Related Questions