Diving into Node.js – Very First App

What do I have till now?

After Node.js is istalled, described in my previous post, I can simply run this command:

stoimenpopov:~# node server.js

and this will start the server with the code within server.js. But what’s the code of server.js?

Following the instructions of Node’s homepage and most of the tutorials I’ve found, I can simply copy/paste the code from the first lines of Node’s page:

var http = require('http');
http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hello World\n');
}).listen(8124, "127.0.0.1");
console.log('Server running at http://127.0.0.1:8124/');

There are several things I find interesting in this code, making it different from JavaScript as we know it. First of all what is

var http = require(‘http’)

and why I need it? What is the purpouse of 8124 and 127.0.0.1?

Node is built in modules and to use one of them you must first include it with require. Just like the example above with require(‘http’). In the same manner you can include every module of Node.

What are the Node’s modules are pretty well described in the API page. Well I’d like to say that the API page is quite insufficient. That is very bad, cause most of the code you’ll need developing a node.js applicatoin isn’t described/explained there.

However is more than obvious that 8124 is the port, while 127.0.0.1 is the IP address of the server, which in this case is the localhost. Thus after running the server and typing http://127.0.0.1:8124/ into your browser you’ll get “Hello World”. This is not enough when the server is running on a remote machine, while you’ve to access it from your local computer.

The first server

As I described the code above shows you an example server. In fact the API page shows a slightly different code:

var http = require('http');
 
http.createServer(function (request, response) {
  response.writeHead(200, {'Content-Type': 'text/plain'});
  response.end('Hello World\n');
}).listen(8124);
 
console.log('Server running at http://127.0.0.1:8124/');

Here the line:

}).listen(8124);

omits the address of the server. It appears to be non-required and the server is supposed to listen on this machine on the given port. To be honest I’m not sure why you’ve to write the server address, except for limit the possible address to this one. However in my case the server was installed on a remote machine indeed, while I was trying to access it from my local machine. So here are some base steps to do before accomplishing this.

1. Changing the IP address

First of all you can omit the IP address. This can help you move the code from one server to another without changing the code.

}).listen(8124, ip_address);

possibly a better solution is:

}).listen(8124);

Node can listen on whatever port you say so this is up to you to decide which port should be opened.

2. Opening the port

While everything’s on the localhost you wont have problems with port opening. If you’d like to access it remotely however, you’ve to open the port. In other words http://127.0.0.1:8124/ is OK without port opening, but http://example.com:8124 – is not!

To open a port in UNIX/Linux you’ve to type this command in the terminal:

iptables -A INPUT -p tcp --dport 8124 -j ACCEPT

don’t forget to change the port number from 8124 to whatever port number you’re using.

3. The first AJAX call

We still cannot make the first AJAX call to the Node server. Here I’m using jQuery because of the easy AJAX interface.

$(document).ready(function() {
	$.ajax({
    	// setup the server address
        url : 'http://example:8124/',
        success : function(response) {
        	// on success
        	alert(response);
		},
        error : function() {
        	// on error
        }
    });
});

After executing this code in a browser there wont be a response. That is because of the remote AJAX calls restriction. To overcome this you’ve to change the returned header from the Node’s server, by adding this:

'Access-Control-Allow-Origin' : '*'

Now server.js will look like this:

var http = require('http');
 
http.createServer(function (request, response) {
	response.writeHead(200, {
		'Content-Type': 'text/plain',
		'Access-Control-Allow-Origin' : '*'
	});
	response.end('Hello World\n');
}).listen(8124);

you can now either load http://example.com:8124 into your browser or to make the AJAX call. In both cases the answer will be “Hello World”

Summary

Now you have a very simple Node.js server. Well it is nothing special as it responses with “Hello World” on every request, but it works remotely.

Soon I’ll describe how to change the server so it can waits to respond until some event is emitted – which is the real power of Node.js.

11 thoughts on “Diving into Node.js – Very First App

  1. Hi Stoimen!

    Thanks for share your knowledge, I’m starting with NodeJs and I think it’s awesome! Sadly there aren’t many tutorials and documentation about this, I’m looking forward for more advanced tutorials.

    Best regards

  2. I have to say that after spending a day in resolving this, i finally succeded due to this line: “‘Access-Control-Allow-Origin’ : ‘*'”.
    That’s a shame that i couldn’t find it anywhere else…

    Thanks.

  3. My Ajax call to node server is not working….

    Node code:
    var http = require(‘http’);
    http.createServer(function (req, res) {

    console.log(‘Request received’);

    res.writeHead(200, {
    ‘Content-Type’: ‘text/plain’,
    ‘Access-Control-Allow-Origin’: ‘*’ // implementation of CORS
    });
    req.on(‘data’, function (chunk) {
    console.log(‘GOT DATA!’);
    });

    res.end(‘{“msg”: “OK”}’); // removed the ‘callback’ stuff

    }).listen(3004);
    console.log(‘Server running at http://localhost:3004/‘);

    html code:

    response here: fill me in

    $(document).ready(function() {
    $.ajax({
    url: ‘http://localhost:3004/’,
    data: ‘{“data”: “TEST”}’,
    success: function (data) {
    alert(‘hi’);
    var ret = jQuery.parseJSON(data);
    $(‘#lblResponse’).html(ret.msg);
    console.log(‘Success: ‘)
    },
    error: function (xhr, status, error) {
    console.log(‘Error: ‘ + error.message);
    $(‘#lblResponse’).html(‘Error connecting to the server.’);
    },
    });
    });

Leave a Reply

Your email address will not be published. Required fields are marked *