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.
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.
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
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.
The REST architecture is based on four concepts and four properties.
Concepts
Properties:
The general, very general, recipe to create a RESTful web application is:
Imagine you are developing a web catalog of products.
Valid URIs and methods:
URI | Method | Meaning |
---|---|---|
http://myFancyCatalog.com/catalog | GET | Returns all products in the catalog |
POST | Adds a new product, the id is generated by the server. | |
http://myFancyCatalog.com/catalog/{id} | GET | Returns product with code id |
PUT | Adds a new product with code id |
Valid URIs and methods (Cont.):
URI | Method | Meaning |
---|---|---|
http://myFancyCatalog.com/catalog/{id} | PUT | Updates a product already present in the catalog |
DELETE | Deletes the product with code id |
When to use each method:
Method | Meaning |
---|---|
GET | To retrieve a description of a resource |
POST | To create a new resource in the server |
PUT | To create/update a resource in the server |
DELETE | To 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?
URI | Method | Meaning |
---|---|---|
http://myFancyCatalog.com/catalog | POST | Adds a new product, the id is generated by the server. |
http://myFancyCatalog.com/catalog/{id} | PUT | Adds/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:
Operation | HTTP Method | Meaning |
---|---|---|
Create | POST | Creates a new resource |
Retrieve | GET | Gets an existing resource |
Update | PUT | Updates an existing resource |
Delete | DELETE | Deletes an existing resource |
We use routing to translate our URIs and Methods table to Express code.
URI | Method | Meaning |
---|---|---|
http://myFancyCatalog.com/ | GET | Returns 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:
URI | Method | Meaning |
---|---|---|
http://myFancyCatalog.com/{id} | GET | Returns 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
Help 3: set a status code with res.status(code), for Not found → code=404.
Exercise
Implement the code for the following service:
URI | Method | Meaning |
---|---|---|
http://myFancyCatalog.com/catalog | POST | Adds 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:
URI | Method | Meaning |
---|---|---|
http://myFancyCatalog.com/catalog/{id} | PUT | Updates 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:
URI | Method | Meaning |
---|---|---|
http://myFancyCatalog.com/catalog/{id} | DELETE | Deletes 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.
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.
Using
This is great! all services you provide are available without regarding the computer language you use to request them.
Code the front-end of the Catalog RESTful applications with the following utilities: