jgozal jgozal - 2 months ago 15
HTTP Question

Sending object from node server to javascript on client side

I have a very simple server like this:

var http = require('http');
var fs = require('fs');

http.createServer(function (req, res) {

res.writeHead(200, { 'Content-Type': 'text/html' });
fs.readFile('index.html', 'utf-8', function (err, content) {
if (err) {
res.end('something went wrong.');
return;
}
res.end(content);
});

}).listen(8080);
console.log("Server running on port 8080.")


This takes care of rendering my html, but now I want to send an object. Something like this:

var arr = [1,2,3];


I want to be able to manipulate this object on the client side using js. So in addition to knowing how to send it from server to client, I would like to know how to receive it in the client, if that makes sense.

I am trying to learn how things happen behind the scene so I do not want to use express.

Answer

The only thing you can exchange via HTTP protocol in general is data. Not objects, not html files, just data. The process of converting objects to data and back is called serialization. For your specific case of simple objects, you can use JSON built-in object to serialize your objects.

At server:

var data = JSON.stringify(arr); 
res.end(data);

At client:

var arr = JSON.parse(data);

As to how to ask and receive data on client, try googling XmlHTTPRequest.

On request, adding fully functional server-side code:

var http = require('http');
var fs = require('fs');

http.createServer(function (req, res) {

  res.writeHead(200, { 'Content-Type': 'text/plain', 'Access-Control-Allow-Origin': '*' });
  var data = JSON.stringify([1, 2, 3]);
  res.end(data);

}).listen(8080);
console.log("Server running on port 8080.")

the Access-Control-Allow-Origin header was only necessary to be able to run your code in console (it is called 'CORS' and means this endpoint can be requested from pages hosted on other domains)