Getting started with Express, the Node.js web application framework

Creating a web-server is a common Node.js project. While the low-level nature of Node can be an asset, it can also be somewhat of a curse. When you are serving static assets, it can be tedious to detect routes, and serve the correct static assets for an entire web page. Examples of static assets are CSS files, images or JavaScript files.

Express.js is a Node module that provides abstraction for these kinds of challenges. This module is a popular one, and used by large companies. There is also strong community support, which makes it a solid choice. While the main goal of Express is to provide an application framework, getting started is simple.

To view the code samples, clone the following git hub repository:

https://github.com/kevinchisholm/getting-started-with-express-the-node-js-web-application-framework

  • (Instructions on how to run the code are available in the Git hub page.) *

package.json

{
  "dependencies": {
    "express": "4.14.0"
  }
}

The package.json for this project is simple: the single dependency is express.

The get() Method

Example # 1:

//reuire the express nodejs module
var express = require('express'),
    //set an instance of exress
    app = express();

//for any requests to the root of the application
app.get('/', function (req, res) {
    //construct the HTML that we will return
var HTML = ''
    + ''
    + ''
        + ''
            + ''
            + 'Example Web Page'
        + ''
        + ''
            + '

This is example # 1

' + '' + ''; //rethrn the HTML to the user's browser res.send(HTML); }); //wait for a connection app.listen(3000, function () { console.log('Server is running. Point your browser to: http://localhost:3000'); });

In example # 1, we call the get() method of the app variable. We pass the string "/" to the get method. This tells Express.js how we want to handle any GET request to the root of the application. GET is an HTTP verb. Other examples are POST and PUT.

In the case of example # 1, we are sending back a simple HTML page. We have created the HTML by constructing a string that represents that HTML code. This happens in the "HTML" variable. We then call the send method of the result object, sending our HTML back to the user.

Run example # 1 in your terminal with the command node example-1.js. And then navigate to http://localhost:3000/ in your browser.

The result of this is : you will see "This is example # 1" in your browser.

The use() method

Example # 2:

//reuire the express nodejs module
var express = require('express'),
    //set an instance of exress
    app = express(),
    //reuire the path nodejs module
    path    = require("path");

//tell express that www is the root of our public web folder
app.use(express.static(path.join(__dirname, 'www')));

//wait for a connection
app.listen(3000, function () {
  console.log('Server is running. Point your browser to: http://localhost:3000');
});

Example # 2 is much shorter than example # 1. The reason for this is that we have not hard-coded our HTML. Instead, we have used the use method of the app object. This method tells Express which folder we want to use for serving static assets. As a result, our JavaScript code is cleaner, and more easy to read. Also, we separate concerns. Instead of hard-coding our HTML in our JavaScript file, we put HTML where it belongs: in an HTML file.

Notice how the web page in example # 2 has an image. I included an image to point out how Express handles this for us. We never had to write any JavaScript code that specifically waits for an image request. There is also a CSS file being served. In both cases, Express understands that WWW is our public web folder and it serves up statics assets as needed. This saves us a lot of time.

Run example # 2 in your terminal with the command node example-2.js. And then navigate to http://localhost:3000/ in your browser.

The result of this is : you will see "This is www/index.html" in your browser. This is a major improvement as the HTML that the user sees is actually served from a static HTML file.

Adding Handlers for a Second Route

Example # 3:

//reuire the express nodejs module
var express = require('express'),
    //set an instance of exress
    app = express(),
    //reuire the path nodejs module
    path    = require("path");

//tell express that www is the root of our public web folder
app.use(express.static(path.join(__dirname, 'www')));

//tell express what to do when the /about route is requested
app.get('/about',function(req,res){
  res.sendFile(path.join(__dirname + '/www/about.html'));
});

//wait for a connection
app.listen(3000, function () {
  console.log('Server is running. Point your browser to: http://localhost:3000');
});

In example # 3, we use the get method to add a handler for when the user requests "/about". In this case, we serve-up "/www/about.html". This is just one example, but we could have added any specific route handlers needed.

Run example # 3 in your terminal with the command node example-3.js. Navigate to http://localhost:3000/ in your browser.

The result of this is : you will see "This is www/index.html" in your browser. Then, click "About" in the upper-right-hand corner. You will see the "About Us" page. You can then click "Home" and "About" over and over, to switch routes. Our JavaScript code in example-1.js handles swtiching between these two routes.

Summary

In this article, we learned the absolute basics of Express.js. We discussed the get() method, as well as the use() method. This Node.js module contains a great deal of power and there is a lot more to talk about. Hopefully, this article has helped you to get started and see how simple Express.js can be to use.

Author

Kevin Chisholm

http://blog.kevinchisholm.com

Share This