Training Guide: Programming in HTML5 with JavaScript and CSS3 Ebook

(Nora) #1

Lesson 1: Getting started with Node.js CHAPTER 8 357


app.get('/', function(request, response){
response.send('Hello World');
});

The request and response objects are the same objects that Node.js provides. The last bit
of code to add is the statements that are required to listen for a request as follows.
var port = 8080;
app.listen(port);
console.log('Listening on port: ' + port);

Your completed app.js file should look like the following.
var express = require('express');
var app = express();

app.get('/', function (request, response) {
response.send('Hello World');
});

var port = 8080;
app.listen(port);
console.log('Listening on port: ' + port);
Save and run the following command to start the web server.
node app

When the application is started, you see a message stating that the application is listening
on port 8080. Open the browser and enter the following URL.
http://localhost:8080/

This request is routed to the function that handles the request, and Hello World is sent to
the response, as shown in Figure 8-8.

FIGURE 8-8 he express application responding to a page requestT

Adding a webpage to the application
Instead of writing JavaScript to render every page, you can create HTML pages that can be
retrieved automatically with a minimum of code. In the app.js file, replace the app.get state-
ment with the following.
app.use(express.static(__dirname + '/public'));
Free download pdf