Contact Us or call 1-877-932-8228


Unlike most of the content in this JavaScript course, many of the XMLHttpRequest demos and exercises in this lesson won't work if you run them locally instead of via a webserver. As such, we ask you to use Node.js to serve HTML, CSS, and JavaScript from your computer. Node.js is a "platform built on Chrome's JavaScript runtime for easily building fast, scalable network applications. Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient, perfect for data-intensive real-time applications that run across distributed devices." Much like PHP, ColdFusion, Microsoft .NET, or JavaServer Pages, Node.js (pronounced to rhyme with "Toad Say Yes") is an application server. You might use Node.js to connect to a database (returning a result set from a query, say, or updating a record); deliver HTML, XML, or JSON content; connect to local files; or serve up static web pages like Apache or another web server.

Installing Node.js

Please refer to the setup instructions for installing and running Node.js here:

Running Node.js

We will use Node.js both as a web server to serve static HTML files and their associated CSS and JavaScript components. We will also use Node.js to serve dynamic responses, which will serve as the back end of our Ajax applications. An Ajax-enabled web page might, for instance, allow the user to display details for a desired person by clicking on that person's name on a list displayed on the page; the click would generate an Ajax call to a "behind the scenes" page that queries a database. The Ajax call carries with it the ID of the desired person's record. We'll use Node.js to serve up the "page" that returns the database query. Let's look at a simple example.

A First Node.js Application & Server

In your class files, navigate to the directory XHR/Demos/nodejs/. In it you will find the following files/directories:

  1. package.json
  2. server.js
  3. HelloWorld.pug

package.json defines this particular Node.js application; most importantly, the file defines the Node.js modules needed for this app. Modules enable functionality - connecting to a database, say, or browsing a directory from the web server - and are usually downloaded via npm, the Node.js package manager. All of the Node.js applications in this course will have all the needed modules already installed.

Navigate to the same directory mentioned above from the command line (Terminal on a Mac, Command Prompt on a Windows PC). To do so, on either Windows or Mac, type cd ("change directory") and the path to the directory. On a PC, you will use backslashes ("\"); on a Mac, you will use forward slashes ("/").

On a PC, for instance, one would type cd c:\webucator\ClassFiles\XHR\Demos\nodejs if the class files were stored in a directory named webucator in the root of the c: drive. A Mac user would type cd ~/Documents/webucator/ClassFiles/XHR/Demos/nodejs if the class files were stored in a directory named webucator inside the user's Documents directory; note that, on a Mac, ~ refers to the root of the current user's directory.

Next, type npm install from the command line: this will download the needed modules, as defined in package.json. Node modules will install to the directory node_modules.

After modules have installed, type npm start to start the application.

When needed, press CTRL+c on the command line to stop the Node.js server instance.

server.js defines the application itself: this is the file that runs when you started the Node.js application, which defines how the application makes use of Node.js modules, and which starts the web server on a specific port. Note the when you open up server.js with your web editor, the last line - app.listen(8080); - starts the web server (an HTTP server) and listens on port 8080 so that, once the application is running, visitors can browse to http://localhost:8080 to view files served by and response routes defined by this application.

server.js also defines a set of response routes; in this example, these are the GET routes /HelloWorld and /HelloWorldPug. Each route is a function in server.js, defining the method (usually GET or POST), the actual route (/HelloWorld, for example), and how to respond, defined as an anonymous function. We will review each of these in detail.

app.get('/HelloWorld', function(req, res) {
			var name = req.param('name') || 'Somebody';
			var respondWith = '<?xml version="1.0" encoding="UTF-8"?>';
			respondWith += "<h1>Hello " + name + "!</h1>";
			res.setHeader('Content-type', 'text/xml');
			return res.send(respondWith);

The first line of code, app.get('/HelloWorld..., defines a GET route, meaning that, once this Node.js application is running, users will be able to visit http://localhost:8080/HelloWorld in their browser to view the response from this route.

var name = req.param('name') || 'Somebody'; attempts to read a GET parameter from the request made for this response route. If the user browses to http://localhost:8080/HelloWorld?name=Jane, for example, then local variable name will have value "Jane". If the user browses to http://localhost:8080/HelloWorld then local variable name will get the default value "Somebody".

The next few lines of code define the response sent back to the browser: we send back XML, encoded as UTF-8, with a single <h1> tag containing Hello [name]. The very last line, return res.send(respondWith);, sends the response back to the browser.

We will also make use of Pug (formerly known as "Jade"), a templating engine for Node.js, which allows us to define some parts of the response in a template file (usually ending with a .pug extension). Let's look at the other response route defined in our server.js file:

app.get('/HelloWorldPug', function(req, res) {
			var name = req.param('name') || 'Somebody';
			res.render('HelloWorld.pug', {
				'name': name
			}, function(err, html) {
			if (err) {
			} else {

Similar to our first example, this response route defines what the user sees when going to http://localhost:8080/HelloWorldPug in their browser. The code which gets the name parameter, or sets its default value, if the parameter is not present, is the same as we saw previously.

Different this time is the manner in which we craft the response sent back to the server. As you might expect, for a more complicated response like a long web page with a considerable volume of content, for example, it quickly becomes unwieldy to build the response string in the response route definition in server.js itself. As such, using Pug templates - as we have done here - allows us to structure much of the response in a separate file, using a simplified syntax.

The line in server.js that starts res.render('HelloWorld.pug', {'name': name}, function(err, html) {... specifies the way in which we return content to the browser. The first parameter tells Node.js that we want to serve up the HelloWorld.pug template as the response for this route. The second parameter ({'name': name}) in our call to render passes our name variable to the template so that the template has the value of name available to it. The final parameter is a callback function by which we actually send back the data; note that we check to see if the template exists and, if not, redirect the user to a "page not found" error. (On a production site our error handling would likely be more robust - checking for more sources of error than just the template not existing.)

In the template HelloWorld.pug:

doctype html
			title Hello World

	h1 Hello #{name}

Pug is a templating engine designed for use with Node.js. It offers a simplified syntax to specify the type of page (an HTML5 page, in our case) and to display content. In our example here, we use Jade to give the page a <title> tag with value Hello World and, on the last line, use interpolation to display the variable name as the value the "Hello" <h1> tag. Recall that the template gets the value of the variable name from the response route: the value defaults to Somebody or gets its value from the GET parameter passed in the request, if present.

You can find more information about the Pug template engine at