Home >>Nodejs Tutorial >Node.js - Express Framework

Node.js - Express Framework

Node.js - Express Framework

Express is a minimal and flexible Web application framework for Node.js which provides a robust set of features for web and mobile applications development. It enables the rapid creation of Web applications based on the Node. Below are some of the main features of Express System –

  1. Requires the setting up of middlewares to address HTTP requests.
  2. Defines a routing table that uses HTTP system and URL to perform different behavior.
  3. Allows to render HTML Pages dynamically based on passing arguments to templates.

Installing Express

Firstly, install the Express framework globally using NPM so that a web application can be built using node terminal.

$ npm install express --save

The command above saves the installation locally in the directory node modules, and creates an express directory within node modules. The following critical modules should be mounted alongside express-

  1. Body-parser− This is a node.js middleware for handling encoded form data from JSON, Raw, Text and URL.
  2. Cookie-parser− Decode the cookie header and fill in req.cookies with a cookie name keyed object.
  3. Multer−This is a middleware node.js for multipart / form-data handling.
$ npm install body-parser --save
$ npm install cookie-parser --save
$ npm install multer –save

Hello world Example

A very simple Express app follows which starts a server and listens for link on port 8081. With Hello World this app replies! For homepage inquiries. It will be responding with a 404 Not Found for any other route.


var data = require(‘data’);
var app = data();
app.get('/', function (req, res) {
res.send('Hello Phptpoint');
})
var server = app.listen(8081, function () {
var host = server.address().address
var port = server.address().port
console.log("Example app listening at http://%s:%s", host, port)
})

Save the above code and run it with the following command in a file called server.js.

$ node server.js

The following output is shown –

Example app listening at http://0.0.0.0:8081

Open http:/127.0.0.1:8081/ to view the result below in any browser.

Nodejs Express

Request & Response

Express application uses a callback feature, the parameters of which are object request and response.

app.get('/', function (req, res)
{
   // --
})
  1. Request Object − The request object represents the HTTP request and has properties for the query string of requests, parameters, body, HTTP headers, etc.
  2. Response Object − Represents the HTTP response an Express app sends when it receives an HTTP request.
  3. You can print req and res objects which provide a lot of HTTP request and response information like cookies, sessions, URLs, etc.

Basic Routing

We saw a simple application for the homepage that serves HTTP requests. Routing refers to specifying how a client request responds to a particular endpoint, which is a URI (or path) and a specific HTTP request form (GET, POST, etc.)

We'll be extending our Hello Phptpoint software to handle more HTTP request forms.


var express = require('express');
var app = express();
// This responds with "Hello Phptpoint" on the homepage
app.get('/', function (req, res) {
console.log("Got a GET request for the homepage");
res.send('Hello GET');
})
// This responds a POST request for the homepage
app.post('/', function (req, res) {
console.log("Got a POST request for the homepage");
res.send('Hello POST');
})
// This responds a DELETE request for the /del_user page.
app.delete('/del_user', function (req, res) {
console.log("Got a DELETE request for /del_user");
res.send('Hello DELETE');
})
// This responds a GET request for the /list_user page.
app.get('/list_user', function (req, res) {
console.log("Got a GET request for /list_user");
res.send('Page Listing');
})
// This responds a GET request for abcd, abxcd, ab123cd, and so on
app.get('/ab*cd', function(req, res) {   
console.log("Got a GET request for /ab*cd");
res.send('Page Pattern Match');
})
var server = app.listen(8081, function () {
var host = server.address().address
var port = server.address().port
console.log("Example app listening at http://%s:%s", host, port)
})

Save the above code and run it with the following command in a file called server.js.

$ node server.js
Output:
Example app listening at http://0.0.0.0:8081

Now you can try various requests at http:/127.0.0.1:8081 to see Server.js generated output. A few screenshots follow showing various responses for various URLs.

Screen that again displays http:/127.0.0.1:8081/list user

Nodejs Express

Screen showing again http://127.0.0.1:8081/abcd

Nodejs Express

Screen showing again http://127.0.0.1:8081/xyz

Nodejs Express

Serving Static Files

Express offers express.static built in middleware to support static files like images, CSS, JavaScript, etc.

To start serving the files directly, you simply need to transfer the directory name where you hold your static stuff, to the express.static middleware. For instance, if you keep your images, CSS, and JavaScript files in a public directory, you can do that –

app.use(express.static('public'));

We'll keep some images as follows in the public / images sub-directory

node_modules
server.js
public/
public/images
public/images/logo.png

Let's modify the "Hello Phptpoint" application to add the static file handling functionality.


var express = require('express');
var app = express();
app.use(express.static('public'));
app.get('/', function (req, res) {
res.send('Hello Phptpoint');
})
var server = app.listen(8081, function () {
var host = server.address().address
var port = server.address().port
console.log("Example app listening at http://%s:%s", host, port)
})

Save the above code to server.js file and run it with the following command.

$ node server.js
Output:
Now, in any browser, open http:/127.0.0.1:8081/images / logo.png and see the following results

Nodejs Express

GET Method

Here is a simple example which uses HTML FORM GET method to move two values. Inside server.js we will use process get router to handle this data.


<html>
<body>
<form action = "http://127.0.0.1:8081/process_get" method = "GET">
First Name: <input type = "text" name = "first_name">  <br>
Last Name: <input type = "text" name = "last_name">
<input type = "submit" value = "Submit">
</form>
</body>
</html>

Let's save the code above in index.htm and modify server.js to handle requests from home page as well as input sent by the HTML form.


var express = require('express');
var app = express();
app.use(express.static('public'));
app.get('/index.htm', function (req, res) {
res.sendFile( __dirname + "/" + "index.htm" );
})
app.get('/process_get', function (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));
})
var server = app.listen(8081, function () {
var host = server.address().address
var port = server.address().port
console.log("Example app listening at http://%s:%s", host, port)
})

Use http:/127.0.0.1:8081/index.htm to access the HTML document will generate the following form –

Output:
You can now enter the first and last name and then click the submit button to see the result.
{"first_name":"John","last_name":"Paul"}

POST Method

Here is a simple example that transfers two values using form HTML FORM POST. Within server.js we can use process get router to handle this data.


<html>
<body>
<form action = "http://127.0.0.1:8081/process_post" method = "POST">
First Name: <input type = "text" name = "first_name"> <br>
Last Name: <input type = "text" name = "last_name">
<input type = "submit" value = "Submit">
</form>
</body>
</html>

Let's save the above code to index.htm and change server.js to handle requests from home page as well as input from the HTML-form.


var express = require('express');
var app = express();
var bodyParser = require('body-parser');
// Create application/x-www-form-urlencoded parser
var urlencodedParser = bodyParser.urlencoded({ extended: false })
app.use(express.static('public'));
app.get('/index.htm', function (req, res) {
res.sendFile( __dirname + "/" + "index.htm" );
})
app.post('/process_post', urlencodedParser, function (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, function () {
var host = server.address().address
var port = server.address().port
console.log("Example app listening at http://%s:%s", host, port)
})

Using http:/127.0.0.1:8081/index.htm to access the HTML document should create the following type–

Output:
You can now type the first and last name and then press the submit button to see the result –
{"first_name":"John","last_name":"Paul"}

File Upload

The following HTML code provides a form for file uploaders. This form has a method attribute set to POST and is set to multipart / form-data attribute enctype.


<html>
<head>
<title> Uploading File Form</title>
</head>
<body>
<h3>File Upload:</h3>
Select a file to upload: <br />
<form action = "http://127.0.0.1:8081/file_upload" method = "POST" 
enctype = "multipart/form-data">
<input type="file" name="file" size="50" />
<br />
<input type = "submit" value = "Upload File" />
</form>
</body>
</html>

Let's save code in index.htm above and change server.js to handle requests from home page as well as uploading data.


var express = require('express');
var app = express();
var fs = require("fs");
var bodyParser = require('body-parser');
var multer  = require('multer');
app.use(express.static('public'));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(multer({ dest: '/tmp/'}));
app.get('/index.htm', function (req, res) {
res.sendFile( __dirname + "/" + "index.htm" );
})
app.post('/file_upload', function (req, res) {
console.log(req.files.file.name);
console.log(req.files.file.path);
console.log(req.files.file.type);
var file = __dirname + "/" + req.files.file.name;
fs.readFile( req.files.file.path, function (err, data) {
fs.writeFile(file, data, function (err) {
if( err ) {
console.log( err );
} else {
response = {
message:'File uploaded successfully',
filename:req.files.file.name
};
}
console.log( response );
res.end( JSON.stringify( response ) );
});
});
})
var server = app.listen(8081, function () {
var host = server.address().address
var port = server.address().port
console.log("Example app listening at http://%s:%s", host, port)
})

Using http:/127.0.0.1:8081/index.htm to access the HTML document should create the following type –

Cookies Management

Using the following middleware method you can send cookies to a Node.js server which can handle the same. Below is a clear example of printing all the cookies the client sends.


var express      = require('express')
var cookieParser = require('cookie-parser')
var app = express()
app.use(cookieParser())
app.get('/', function(req, res) {
console.log("Cookies: ", req.cookies)
})
app.listen(8081)