Overview of expressJS, installation and Request-response model

Last updated on Jan 19 2023
Prabhas Ramanathan

Express.js is a web framework for Node.js. It is a fast, robust and asynchronous in nature.
Our Express.js tutorial includes all topics of Express.js such as Express.js installation on windows and linux, request object, response object, get method, post method, cookie management, scaffolding, file upload, template etc.

Table of Contents

What is Express.js

Express is a fast, assertive, essential and moderate web framework of Node.js. You can assume express as a layer built on the top of the Node.js that helps manage a server and routes. It provides a robust set of features to develop web and mobile applications.
Let’s see some of the core features of Express framework:
• It can be used to design single-page, multi-page and hybrid web applications.
• It allows to setup middlewares to respond to HTTP Requests.
• It defines a routing table which is used to perform different actions based on HTTP method and URL.
• It allows to dynamically render HTML Pages based on passing arguments to templates.

Why use Express

• Ultra fast I/O
• Asynchronous and single threaded
• MVC like structure
• Robust API makes routing easy

How does Express look like

Let’s see a basic Express.js app.
File: basic_express.js

1. var express = require('express'); 
2. var app = express(); 
3. app.get('/', function (req, res) { 
4. res.send('Welcome to tecklearn!'); 
5. }); 
6. var server = app.listen(8000, function () { 
7. var host = server.address().address; 
8. var port = server.address().port; 
9. console.log('Example app listening at http://%s:%s', host, port); 
10. });

Install Express.js

Firstly, you have to install the express framework globally to create web application using Node terminal. Use the following command to install express framework globally.
npm install -g express
Installing Express
Use the following command to install express:
npm install express –save
The above command install express in node_module directory and create a directory named express inside the node_module. You should install some other important modules along with express. Following is the list:
• body-parser: This is a node.js middleware for handling JSON, Raw, Text and URL encoded form data.
• cookie-parser: It is used to parse Cookie header and populate req.cookies with an object keyed by the cookie names.
• multer: This is a node.js middleware for handling multipart/form-data.
npm install body-parser –save
npm install cookie-parser –save
npm install multer –save

Express.js App Example

Let’s take a simple Express app example which starts a server and listen on a local port. It only responds to homepage. For every other path, it will respond with a 404 Not Found error.

1. File: express_example.js 
1. var express = require('express'); 
2. var app = express(); 
3. app.get('/', function (req, res) { 
4. res.send('Welcome to tecklearn'); 
5. }) 
6. var server = app.listen(8000, function () { 
7. var host = server.address().address 
8. var port = server.address().port 
9. console.log("Example app listening at http://%s:%s", host, port) 
10. })

 

Express.js Request Object

Express.js Request and Response objects are the parameters of the callback function which is used in Express applications.
The express.js request object represents the HTTP request and has properties for the request query string, parameters, body, HTTP headers, and so on.

Syntax:

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

Express.js Request Object Properties

The following table specifies some of the properties associated with request object.

Index Properties Description
1. req.app This is used to hold a reference to the instance of the express application that is using the middleware.
2. req.baseurl It specifies the URL path on which a router instance was mounted.
3. req.body It contains key-value pairs of data submitted in the request body. By default, it is undefined, and is populated when you use body-parsing middleware such as body-parser.
4. req.cookies When we use cookie-parser middleware, this property is an object that contains cookies sent by the request.
5. req.fresh It specifies that the request is “fresh.” it is the opposite of req.stale.
6. req.hostname It contains the hostname from the “host” http header.
7. req.ip It specifies the remote IP address of the request.
8. req.ips When the trust proxy setting is true, this property contains an array of IP addresses specified in the ?x-forwarded-for? request header.
9. req.originalurl This property is much like req.url; however, it retains the original request URL, allowing you to rewrite req.url freely for internal routing purposes.
10. req.params An object containing properties mapped to the named route ?parameters?. For example, if you have the route /user/:name, then the “name” property is available as req.params.name. This object defaults to {}.
11. req.path It contains the path part of the request URL.
12. req.protocol The request protocol string, “http” or “https” when requested with TLS.
13. req.query An object containing a property for each query string parameter in the route.
14. req.route The currently-matched route, a string.
15. req.secure A Boolean that is true if a TLS connection is established.
16. req.signedcookies When using cookie-parser middleware, this property contains signed cookies sent by the request, unsigned and ready for use.
17. req.stale It indicates whether the request is “stale,” and is the opposite of req.fresh.
18. req.subdomains It represents an array of subdomains in the domain name of the request.
19. req.xhr A Boolean value that is true if the request’s “x-requested-with” header field is “xmlhttprequest”, indicating that the request was issued by a client library such as jQuery

Request Object Methods

Following is a list of some generally used request object methods:
req.accepts (types)
This method is used to check whether the specified content types are acceptable, based on the request’s Accept HTTP header field.
Examples:

1. req.accepts('html'); 
2. //=>?html? 
3. req.accepts('text/html'); 
4. // => ?text/html?

req.get(field)

This method returns the specified HTTP request header field.
Examples:

1. req.get('Content-Type'); 
2. // => "text/plain" 
3. req.get('content-type'); 
4. // => "text/plain" 
5. req.get('Something'); 
6. // => undefined

req.is(type)

This method returns true if the incoming request’s “Content-Type” HTTP header field matches the MIME type specified by the type parameter.
Examples:

1. // With Content-Type: text/html; charset=utf-8 
2. req.is('html'); 
3. req.is('text/html'); 
4. req.is('text/*'); 
5. // => true

req.param(name [, defaultValue])

This method is used to fetch the value of param name when present.
Examples:

1. // ?name=sasha 
2. req.param('name') 
3. // => "sasha" 
4. // POST name=sasha 
5. req.param('name') 
6. // => "sasha" 
7. // /user/sasha for /user/:name 
8. req.param('name') 
9. // => "sasha"

Express.js Response Object

The Response object (res) specifies the HTTP response which is sent by an Express app when it gets an HTTP request.

What it does

• It sends response back to the client browser.
• It facilitates you to put new cookies value and that will write to the client browser (under cross domain rule).
• Once you res.send() or res.redirect() or res.render(), you cannot do it again, otherwise, there will be uncaught error.

Response Object Properties

Let’s see some properties of response object.

Index Properties Description
1. res.app It holds a reference to the instance of the express application that is using the middleware.
2. res.headersSent It is a Boolean property that indicates if the app sent HTTP headers for the response.
3. res.locals It specifies an object that contains response local variables scoped to the request

Response Object Methods

Following are some methods:

Response Append method

Syntax:

1. res.append(field [, value])
This method appends the specified value to the HTTP response header field. That means if the specified value is not appropriate then this method redress that.

Examples:

1. res.append(‘Link’, [‘<http://localhost/>’, ‘<http://localhost:3000/>’]);
2. res.append(‘Warning’, ‘199 Miscellaneous warning’);

Response Attachment method

Syntax:

1. res.attachment([filename])
This method facilitates you to send a file as an attachment in the HTTP response.

Examples:

1. res.attachment(‘path/to/js_pic.png’);

Response Cookie method

Syntax:

1. res.cookie(name, value [, options])
This method is used to set a cookie name to value. The value can be a string or object converted to JSON.

Examples:

1. res.cookie(‘name’, ‘Aryan’, { domain: ‘.xyz.com’, path: ‘/admin’, secure: true });
2. res.cookie(‘Section’, { Names: [Aryan,Sushil,Priyanka] });
3. res.cookie(‘Cart’, { items: [1,2,3] }, { maxAge: 900000 });

Response ClearCookie method

Syntax:

1. res.clearCookie(name [, options])
As the name specifies, the clearCookie method is used to clear the cookie specified by name.

Examples:

To set a cookie
1. res.cookie(‘name’, ‘Aryan’, { path: ‘/admin’ });

To clear a cookie:

1. res.clearCookie(‘name’, { path: ‘/admin’ });
Response Download method

Syntax:

1. res.download(path [, filename] [, fn])
This method transfers the file at path as an “attachment” and enforces the browser to prompt user for download.

Example:

1. res.download(‘/report-12345.pdf’);

Response End method

Syntax:

1. res.end([data] [, encoding])
This method is used to end the response process.

Example:

1. res.end();
2. res.status(404).end();

Response Format method

Syntax:

1. res.format(object)
This method performs content negotiation on the Accept HTTP header on the request object, when present.

Example:

1. res.format({ 
2. 'text/plain': function(){ 
3. res.send('hey'); 
4. }, 
5. 'text/html': function(){ 
6. res.send(' 
7. hey'); 
8. }, 
9. 'application/json': function(){ 
10. res.send({ message: 'hey' }); 
11. }, 
12. 'default': function() { 
13. // log the request and respond with 406 
14. res.status(406).send('Not Acceptable'); 
15. } 
16. });

 

Response Get method

Syntax:

1. res.get(field)
This method provides HTTP response header specified by field.

Example:

1. res.get(‘Content-Type’);

Response JSON method:

Syntax:

1. res.json([body])
This method returns the response in JSON format.

Example:

1. res.json(null)
2. res.json({ name: ‘ajeet’ })

Response JSONP method

Syntax:

1. res.jsonp([body])
This method returns response in JSON format with JSONP support.

Examples:

1. res.jsonp(null)
2. res.jsonp({ name: ‘ajeet’ })

Response Links method

Syntax:

1. res.links(links)
This method populates the response?s Link HTTP header field by joining the links provided as properties of the parameter.

Examples:

1. res.links({ 
2. next: 'http://api.rnd.com/users?page=5', 
3. last: 'http://api.rnd.com/users?page=10' 
4. });

Response Location method

Syntax:

1. res.location(path)
This method is used to set the response location HTTP header field based on the specified path parameter.

Examples:

1. res.location(‘http://xyz.com’);

Response Redirect method

Syntax:

1. res.redirect([status,] path)
This method redirects to the URL derived from the specified path, with specified HTTP status

Examples:

1. res.redirect(‘http://example.com’);

Response Render method

Syntax:

1. res.render(view [, locals] [, callback])
This method renders a view and sends the rendered HTML string to the client.

Examples:

1. // send the rendered view to the client 
2. res.render('index'); 
3. // pass a local variable to the view 
4. res.render('user', { name: 'aryan' }, function(err, html) { 
5. // ... 
6. });

Response Send method

Syntax:

1. res.send([body])
This method is used to send HTTP response.

Examples:

1. res.send(new Buffer('whoop')); 
2. res.send({ some: 'json' }); 
3. res.send(' 
4. .....some html 
5. ');

Response sendFile method

Syntax:

1. res.sendFile(path [, options] [, fn])
This method is used to transfer the file at the given path. It sets the Content-Type response HTTP header field based on the filename’s extension.

Examples:

1. res.sendFile(fileName, options, function (err) { 
2. // ... 
3. });

Response Set method

Syntax:

1. res.set(field [, value])
This method is used to set the response of HTTP header field to value.

Examples:

 

1. res.set('Content-Type', 'text/plain'); 
2. 
3. res.set({ 
4. 'Content-Type': 'text/plain', 
5. 'Content-Length': '123', 
6. })

Response Status method

Syntax:

1. res.status(code)
This method sets an HTTP status for the response.

Examples:

1. res.status(403).end();
2. res.status(400).send(‘Bad Request’);

Response Type method

Syntax:

1. res.type(type)
This method sets the content-type HTTP header to the MIME type.

Examples:

1. res.type(‘.html’); // => ‘text/html’
2. res.type(‘html’); // => ‘text/html’
3. res.type(‘json’); // => ‘application/json’
4. res.type(‘application/json’); // => ‘application/json’
5. res.type(‘png’); // => image/png:

So, this brings us to the end of blog. This Tecklearn ‘Overview of expressJS, installation and Request-response model’ blog helps you with commonly asked questions if you are looking out for a job in NodeJS Programming. If you wish to learn NodeJS and build a career in NodeJS Programming domain, then check out our interactive, Node.js Training, that comes with 24*7 support to guide you throughout your learning period.

Node.js Training

About the Course

Tecklearn’s Node.js certification training course familiarizes you with the fundamental concepts of Node.js and provides hands-on experience in building applications efficiently using JavaScript. It helps you to learn how to develop scalable web applications using Express Framework and deploy them using Nginx. You will learn how to build applications backed by MongoDB and gain in-depth knowledge of REST APIs, implement testing, build applications using microservices architecture and write a real-time chat application using Socket IO. Accelerate your career as a Node.js developer by enrolling into this Node.js training.

Why Should you take Node.js Training?

• As per Indeed.com data, the average salary of Node.js developer is about $115000 USD per annum.
• IBM, LinkedIn, Microsoft, GoDaddy, Groupon, Netflix, PayPal, SAP have adopted Node.js – ITJungle.com
• There are numerous job opportunities for Node.js developers worldwide. The job market and popularity of Node.js is constantly growing over the past few years.

What you will Learn in this Course?

Introduction to Node.js

• What is Node.js?
• Why Node.js?
• Installing NodeJS
• Node in-built packages (buffer, fs, http, os, path, util, url)
• Node.js Modules
• Import your own Package
• Node Package Manager (NPM)
• Local and Global Packages

File System Module and Express.js

• File System Module
• Operations associated with File System Module
• JSON Data
• Http Server and Client
• Sending and receiving events with Event Emitters
• Express Framework
• Run a Web Server using Express Framework
• Routes
• Deploy application using PM2 and Nginx

Work with shrink-wrap to lock the node module versions

• What is shrink-wrap
• Working with npmvet
• Working with outdated command
• Install NPM Shrinkwrap

Learn asynchronous programming

• Asynchronous basics
• Call-back functions
• Working with Promises
• Advance promises
• Using Request module to make api calls
• Asynchronous Commands

Integration with MongoDB and Email Servers

• Introduction to NoSQL Databases and MongoDB
• Installation of MongoDB on Windows
• Installation of Database GUI Viewer
• Inserting Documents
• Querying, Updating and Deleting Documents
• Connect MongoDB and Node.js Application
• Exploring SendGrid
• Sending emails through Node.js application using SendGrid

REST APIs and GraphQL

• REST API
• REST API in Express
• Postman
• MongoDB Driver API
• Express Router
• Mongoose API
• GraphQL
• GraphQL Playground

Building Node.js Applications using ES6

• ES6 variables
• Functions with ES6
• Import and Export withES6
• Async/Await
• Introduction to Babel
• Rest API with ES6
• Browsing HTTP Requests with Fetch
• Processing Query String
• Creating API using ES6
• Building Dashboard API
• Creating dashboard UI with EJS
• ES6 Aside: Default Function Parameters
• Data Validation and Sanitization

User Authentication and Application Security

• Authentication
• Types of Authentication
• Session Vs Tokens
• JSON Web Tokens
• Bcrypt
• Node-local storage

Understand Buffers, Streams, and Events

• Using buffers for binary data
• Flowing vs. non-flowing streams
• Streaming I/O from files and other sources
• Processing streams asynchronously
• File System and Security

Build chat application using Socket.io

• Getting Started
• Adding Socket.io To Your App
• Exploring the Front-end
• Sending Live Data Back & Forth
• Creating the Front-end UI
• Showing Messages In App
• Working with Time
• Timestamps
• Show Message Time In Chat App
• Chat application Project

Microservices Application

• Why Microservices?
• What is Microservices?
• Why Docker?
• What is Docker?
• Terminologies in Docker
• Child Processes
• Types of child process

 

0 responses on "Overview of expressJS, installation and Request-response model"

Leave a Message

Your email address will not be published. Required fields are marked *