Sam
Sam

Reputation: 3559

How to send the value of a variable from Node.js to the browser?

I don't understand why I can't get the value of "i" in the browser. I got this Erreur 101 (net::ERR_CONNECTION_RESET)

var http = require('http');
var i=0;

http.createServer(function (req, res) {
    i++;
    res.writeHeader(200, {'Content-Type': 'text/plain'});
    res.write(i);
    res.end();
}).listen(80, "127.0.0.1");

But it does work if :

res.write("i =" + i);

Thank you

Upvotes: 0

Views: 310

Answers (1)

fardjad
fardjad

Reputation: 20394

Short Answer:

Because the type of i is number.

Long Answer:

Take a look at Socket.prototype.write definition:

Socket.prototype.write = function(chunk, encoding, cb) {
  if (typeof chunk !== 'string' && !Buffer.isBuffer(chunk))
    throw new TypeError('invalid data');
  return stream.Duplex.prototype.write.apply(this, arguments);
};

Upvotes: 2

Related Questions