We now have a youtube channel. Subscribe!

Node.js | Express Framework

Node.js | Express Framework


Hello folks! welcome back to a new edition of our tutorial on Node.js. In this section of our tutorial on Node.js, we will be studying about Node.js Express Framework.

Express Overview

Express is a minimal and flexible Node web application framework that makes available a robust set of features to develop web and mobile applications. It speeds up the rapid development of Node based applications.

Features of Express Framework

Following are some of the core features of express framework -

  • Allows for setting 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 for dynamically rendering Html pages based on passing arguments to templates.

Installation of Express Framework

First, install the Express framework globally making use of npm so that it can be used to build a web application making use of node terminal.

$ npm install express --save

The above command saves the Installation locally in node_modules directory and then create a directory express in node_modules. You need to install the following important modules along with express -

  • body-parser - A node.js middleware to handle JSON, Raw, Text and encoded URL form data.
  • cookie-parser - Parses Cookie header and pupulate req.cookies making use of an object keyed by the name of the cookie.
  • multer - A node.js middleware used for handling multipart/form-data.

$ npm install body-parser --save
$ npm install cookie-parser --save
$ npm install multer --save

HelloWorld Example

The following is a basic Express app which starts a server and listens on port 8081 for a connection. This app responds with Hello World! for request to the homepage. For all other path, it is going to respond with a 404 Not Found.

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

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

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 program in a js file, server.js and run it using the following command -

$ node server.js

Output

Verify the output.

Example app listening at http://0.0.0.0:8081

Open http://127.0.0.1:8081/ in any browser to see the following result -

node_sample


Request and Response

Express application makes use of a callback function whose parameters are request and response objects.

app.get('/', function (req, res) {
   // --
})

  • Request Object - This represents the HTTP request and has properties for the request query string, parameters, HTTP headers, body, and so on.
  • Response Object - This represents the HTTP response which an Express app sends when it gets an HTTP request.

You can print the req and res objects which provide a lot of information related to HTTP request and response including cookie, URL, sessions, etc.

Basic Routing

We've seen a basic application which serves HTTP request for the homepage of the app. Routing is a process of determining how an application responds to a client request to a particular endpoint, which is a URL (or path) and a specific HTTP request method (POST, GET, and so on).

Example

We will extend our Hello World program to handle more types of HTTP requests -

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

// This responds with "Hello World" 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 program in a js file, server.js and run it using the following command -

$ node server.js

Output

Verify the output.

Example app listening at http://0.0.0.0:8081

Now, you can try different request using any browser to open http://127.0.0.1:8081 to see the output generated by server.js. Following are screenshots showing various responses for different URLs.

Screenshot displaying response for the URL http://127.0.0.1:8081/list_user -

nodejs_sample2

Screenshot displaying response for the URL http://127.0.0.1:8081/abcd -

nodejs_sample3

Screenshot displaying response for the URL http://127.0.0.1:8081/abcdefg -

nodejs_sample4


Serving Static Files

Express offers a built-in middleware named express.static to serve static files, such as images, CSS, JavaScript, etc.

To start serving the file directly, you need to pass directory name where you stored your static files to the express.static middleware. For example, if you keep your images, CSS, and JavaScript assets in a directory named public, you can do this -

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

We will keep a few images in public/images sub-directory as follows -

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

Example

Let us modify Hello World! program to add the functionality to handle static files -

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

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

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

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 program in a js file, server.js and run it using the following command -

$ node server.js

Output

Open http://127.0.0.1:8081/images/logo.png in any browser to see the following output.

nodejs_sample5

GET Method

Here is a simple example which passes two values using HTML FORM GET method. We will use process_get router inside server.js to handle this input.

<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 us save the above program in index.html and modify the server.js file to handle home page request and also the 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)
})

Accessing the HTML document making use of http://127.0.0.1:8081/index.html is going to generate the following form -

First Name:
Last Name:

Now you can input the First and Last Name and then click on the submit button to see the result and it should return the following result -

{"first_name":"John","last_name":"Paul"}


POST Method

Here is a simple example which passes two values utilizing HTML FORM POST method. We will be using process_post router inside server.js to handle this input.

<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 program in index.html and modify server.js to handle home page requests and also input sent by 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)
})

Accessing the HTML document making use of http://127.0.0.1:8081/index.html is going to generate the following form -

First Name:
Last Name:

Now you can input the First and Last Name and then click on the submit button to see the result and it should return the following result -

{"first_name":"John","last_name":"Paul"}

File Upload

Following Html code creates a file uploader form. This form has method attribute set to POST and enctype set to multipart/form-data.

<html>
   <head>
      <title>File Uploading 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 the above program in index.html and modify server.js to handle home page requests and also file upload -

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)
})

Accessing the HTML document making use of http://127.0.0.1:8081/index.html is going to generate the following form -

File Upload:
Select a file to upload: 

NOTE: This is just dummy form and would not work, but it must work at your server.

Cookies Management

You can send cookies to a Node.js server which can handle the same making use of the following middleware option.

Example

Following is a simple example to print all the cookies sent by the client -

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)


Alright guys! This is where we are going to be rounding up for this tutorial. In our next tutorial, we will be studying about Node.js Request Object.

Feel free to ask your questions where necessary and we will attend to them as soon as possible. If this tutorial was helpful to you, you can use the share button to share this tutorial.

Follow us on our various social media platforms to stay updated with our latest tutorials. You can also subscribe to our newsletter in order to get our tutorials delivered directly to your emails.

Thanks for reading and bye for now.

Post a Comment

Hello dear readers! Please kindly try your best to make sure your comments comply with our comment policy guidelines. You can visit our comment policy page to view these guidelines which are clearly stated. Thank you.
© 2022 ‧ WebDesignTutorialz. All rights reserved. Developed by Jago Desain