Web Development

Server Side

ExpressJS

Óscar Belmonte Fernández

Universitat Jaume I

Introduction

To create the server part of a web application using NodeJS is tedious.

ExpressJS easy the creation of the server part of our web applications.

We will apply the RESRful architectural style to create the server part of our applications, so need to know the basic principles of this architecture.

Content

  1. Installing Express using npm.
  2. First web application with Express.
  3. Basic routing.
  4. RESTfull web services in a nutshell.
  5. Routing.
  6. Serving static files.
  7. Summary.
  8. Exercises.

Installing Express using npm

To install, just open a terminal and write:


npm install express --save
                

npm will search for Express and download it in your current folder.

You can check for it in the node_modules folder.

First web application with Express

Create a new javascript (firstExpress.js) file and type in the following code:


var express = require('express');
var app = express();
var port = 3000;

app.get('/', function (req, res) {
    res.send('Hello World!');
});

var server = app.listen(port, function () {
    console.log('Server running at http://127.0.0.1:' + port);
});
                

To start the server, type in a terminal:


node firstExpress.js
Server running at http://127.0.0.1:3000
                

Basic routing

Let's take a close look into the code. First, we load the Express module


var app = express();
                

Then we describe what to do when a GET to the route "/" is requested.


app.get('/', function (req, res) {
    res.send('Hello World!');
});
                

We send a wellcome string to the client.

Routing is the mechanism to respond to client's request to a particular URI and by means of a particular HTTP method, also konwn as HTTP verbs.

app.METOD(PATH, HANDLER)


app.get('/', function (req, res) {
    res.send('Hello World!');
});
                

This example shows how to respond when someone requests the URI http://localhost:3000/ using a GET method. The handler is a javascript function which is executed to generate the response.

RESTfull web services in a Nutshell

The REST architecture is based on four concepts and four properties.

Concepts

  1. Resource: Any piece of information accessible by means of the HTTP protocol. Examples: a web page, a pdf file, an entry in a database table, a picture and so on.
  2. URIs: A string used to identify the name of a resource. Exaple: http://www3.uji.es/~belfern.
  3. Representation: The same resource, an entry in database table, can be represented as plain text, a json file, an xml file, and so on.
  4. Links: Any resource can be linked to any other resources by links.

Properties:

  1. Addressable: Any resource must have one or more URIs pointing to it.
  2. Stateless: Serves do not remember anything between consecutive requests.
  3. Connection: Anything is connected in a web application.
  4. Uniform interface: HTTP methods and, request and response headers.

The general, very general, recipe to create a RESTful web application is:

  1. To determine the resources of your application.
  2. To determine the valid representations for the resources.
  3. To define the URIs to access to the resources.
  4. To determine the valid HTTP methods to access the resources.
  5. To determine the links between different resources.

Imagine you are developing a web catalog of products.

  1. Resources: Each product in the catalog.
  2. Representations: We determine json and xml as valid representations.
  3. URIs and methods in the following table.
  4. Links: Any product has a link pointing to the next product in the catalog.

Valid URIs and methods:

URIMethodMeaning
http://myFancyCatalog.com/catalogGETReturns all products in the catalog
POSTAdds a new product, the id is generated by the server.
http://myFancyCatalog.com/catalog/{id}GETReturns product with code id
PUTAdds a new product with code id

Valid URIs and methods (Cont.):

URIMethodMeaning
http://myFancyCatalog.com/catalog/{id}PUTUpdates a product already present in the catalog
DELETEDeletes the product with code id

When to use each method:

MethodMeaning
GETTo retrieve a description of a resource
POSTTo create a new resource in the server
PUTTo create/update a resource in the server
DELETETo remove a resource from the server

There are other HTTP methods, but these correspond with the basic CRUD operations: Create, Retrieve, Update and Delete.

Which is the difference between the POST and PUT methods when adding a new resource?

URIMethodMeaning
http://myFancyCatalog.com/catalogPOSTAdds a new product, the id is generated by the server.
http://myFancyCatalog.com/catalog/{id}PUTAdds/Updates a new product with code id

With PUT we provide (decide) the URI of the new resource.

With POST we do not, the server will generate an id for us.

Usually the CRUD operations are mapped to HTTP Methods following this table:

OperationHTTP MethodMeaning
CreatePOSTCreates a new resource
RetrieveGETGets an existing resource
UpdatePUTUpdates an existing resource
DeleteDELETEDeletes an existing resource

Routing

We use routing to translate our URIs and Methods table to Express code.

URIMethodMeaning
http://myFancyCatalog.com/GETReturns all products in the catalog

var catalog = new Object(); // A Map of javascript Objects.
catalog[0] = {id:0, name: "USB drive", price: 10};

app.get("/", function(req,res) {
    res.json(catalog);
});
                

Exercise: Implement the code for the following service:

URIMethodMeaning
http://myFancyCatalog.com/{id}GETReturns the product with code id

app.get("/catalog/:id", function(req, res, next) {
    // Add your code here.
});
                

Help 1: to get the request parameter id use req.params.id

Help 2: the third parameter in the function, next, is used to throw an error. So, if there is no product with code id you can throw an error next("No product with code " + id + " found.");.

Help 3: set a status code with res.status(code), for Not found → code=404.

Exercise

Implement the code for the following service:

URIMethodMeaning
http://myFancyCatalog.com/catalogPOSTAdds a new product to the catalog

app.post("/catalog", function(req, res, next) {
    // Add your code here.
});
                

To gain access to the body of the request, install body-parser dependency on your project: npm install --save body-parser.


var bodyParser = require("body-parser");
app.use(bodyParser.json());
                

Now, you can get the body of the request doing: req.body.

Exercise

Implement the code for the following service:

URIMethodMeaning
http://myFancyCatalog.com/catalog/{id}PUTUpdates an existing product with code id in the catalog

app.put("/catalog/:id", function(req, res, next) {
    // Add your code here.
});
                

Exercise

Implement the code for the following service:

URIMethodMeaning
http://myFancyCatalog.com/catalog/{id}DELETEDeletes an existing product with code id in the catalog

app.delete("/catalog/:id", function(req, res, next) {
    // Add your code here.
});
                

Congratulations! you have written your first RESTful applications.

Serving static files

Express provides an easy way to serve static files:


app.use(express.static("/../node_modules"));
app.use(express.static('/public'));
                

With this, express will serve the files in the /../node_modules and /public folders.

Summary

Using Express you now are able to code all the back-end (server side) of your web appliapplication using the RESTful architectural style.

This is great! all services you provide are available without regarding the computer language you use to request them.

Exercises

Code the front-end of the Catalog RESTful applications with the following utilities:

  1. Add a button to each product to remove it.
  2. Add a button to update the details of a product.
  3. Improve the interface to add new products.