0

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.

3 Answers 3

1

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)

Sign up to request clarification or add additional context in comments.

2 Comments

I tried doing it this way but when doing the ajax request on the client side I would never receive the data. This is my request on the client side: gist.github.com/DevKiddo/dac2d21b93a0bc587629350673cc51dd. I would be grateful if you could create a reproducible example
Edited my answer to provide fully functional data sender. Your code then prints [1,2,3] when run in console.
0

Simply change the response type and stringify the JSON:

http.createServer(function (req, res) {

    var arr = [1,2,3];
    res.writeHead(200, { 'Content-Type': 'application/json'});
    res.end(JSON.stringify(content), 'utf-8');

}).listen(8080);

2 Comments

how would you call this from the client side? I did this but not console logging anything gist.github.com/DevKiddo/dac2d21b93a0bc587629350673cc51dd
I've comment on Gist. Using JSON.parse you get the JSON file: JSON.parse(xmlhttp.responseText).
0

Ok so seems like I was doing a few things wrong. It mainly had to do with the routing on the server. This is what I had tried to do:

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

http.createServer(function (req, res) {

  var arr = [1, 2, 3];
    res.writeHead(200, { 'Content-Type': 'application/json' });
    res.end(JSON.stringify(arr), 'utf-8');

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

And on client side I had something like this:

xmlhttp = new XMLHttpRequest();
   xmlhttp.open("GET","http://localhost:8080/", true);
   xmlhttp.onreadystatechange=function(){
         if (xmlhttp.readyState==4 && xmlhttp.status==200){
          console.log(JSON.parse(xmlhttp.responseText));
         }
   }
   xmlhttp.send();

For some reason, the console.log would never happen and I would just get the array printed on the page. But by adding some routes to my server like this, it worked:

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

http.createServer(function (req, res) {

   if (req.method === 'GET' && req.url === '/') {

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

  if (req.method === 'GET' && req.url === '/data') {
    var arr = [1, 2, 3];
    res.writeHead(200, { 'Content-Type': 'application/json' });
    res.end(JSON.stringify(arr), 'utf-8');
  }



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

1 Comment

http is great if you want to develop some specific, barebones service around http protocol. If you want to actually serve different files and pages and data, I suggest you look into Express

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.