<tech> brunch ;


Express Api for Node | Quick Reference

Express is a minimal and flexible Node.js web application framework that provides a robust set of features to develop web and mobile applications. It facilitates the rapid development of Node based Web applications. It has been written on top of Node’s HTTP module. It makes writing REST(representational state transfer) API easy and with minimum lines of codes.


Flow Diagram

Following are some of the core features of Express framework −

  • Allows to set up middlewares to respond to HTTP Requests.

  • Defines a routing table which is used to perform different actions based on HTTP Method and URL.

  • Allows to dynamically render HTML Pages based on passing arguments to templates.

From the perspective of concepts related to REST, we have GET, POST, PUT and DELETE type of requests over HTTP protocol.

  • GET - This is used to provide a read only access to a resource.

  • PUT - This is used to create a new resource.

  • DELETE - This is used to remove a resource.

  • POST - This is used to update a existing resource or create a new resource.

To get started we just need to install express framework in our application.

1
npm install --save express // --save flag is to save the entry in our package.json.

An example, which justifies everything that why its used. It’s simple and self explanatory.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
var express = require('express');
var app = express();

app.use(express.static('public'));
app.get('/index.htm', (req, res) => {
res.sendFile( __dirname + "/" + "index.html" );
})

app.get('/process_get', (req, res) => {
// Prepare output in JSON format
response = {
first_name:req.query.first_name,
last_name:req.query.last_name
};
console.log(response);
res.end(JSON.stringify(response));
});

app.post('/process_post', (req, res) => {
// Prepare output in JSON format
response = {
first_name:req.body.first_name,
last_name:req.body.last_name
};
console.log(response);
res.end(JSON.stringify(response));
});

var server = app.listen(8081, () => {
var host = server.address().address
var port = server.address().port
console.log("Example app listening at http://%s:%s", host, port)

});

In the similar fashion, we can have PUT and DELETE requests also written using Express framwework.

On a differnt Note: We often use Nodemon in Node, to allow our server to reflect changes as soon as it is done. Along with Nodemon, we often use JOI for validation. Joi is maintained by Hapi.js project. Even though hapi.js is a web framework by itself, Joi is independent and can be used in any type of node project. This is great for people using express or restify.
What makes it even more interesting is that, besides user validation, it can be used to define database schemas as well