
Domains
Agile Management
Master Agile methodologies for efficient and timely project delivery.
View All Agile Management Coursesicon-refresh-cwCertifications
Scrum Alliance
16 Hours
Best Seller
Certified ScrumMaster (CSM) CertificationScrum Alliance
16 Hours
Best Seller
Certified Scrum Product Owner (CSPO) CertificationScaled Agile
16 Hours
Trending
Leading SAFe 6.0 CertificationScrum.org
16 Hours
Professional Scrum Master (PSM) CertificationScaled Agile
16 Hours
SAFe 6.0 Scrum Master (SSM) CertificationAdvanced Certifications
Scaled Agile, Inc.
32 Hours
Recommended
Implementing SAFe 6.0 (SPC) CertificationScaled Agile, Inc.
24 Hours
SAFe 6.0 Release Train Engineer (RTE) CertificationScaled Agile, Inc.
16 Hours
Trending
SAFe® 6.0 Product Owner/Product Manager (POPM)IC Agile
24 Hours
ICP Agile Certified Coaching (ICP-ACC)Scrum.org
16 Hours
Professional Scrum Product Owner I (PSPO I) TrainingMasters
32 Hours
Trending
Agile Management Master's Program32 Hours
Agile Excellence Master's ProgramOn-Demand Courses
Agile and ScrumRoles
Scrum MasterTech Courses and Bootcamps
Full Stack Developer BootcampAccreditation Bodies
Scrum AllianceTop Resources
Scrum TutorialProject Management
Gain expert skills to lead projects to success and timely completion.
View All Project Management Coursesicon-standCertifications
PMI
36 Hours
Best Seller
Project Management Professional (PMP) CertificationAxelos
32 Hours
PRINCE2 Foundation & Practitioner CertificationAxelos
16 Hours
PRINCE2 Foundation CertificationAxelos
16 Hours
PRINCE2 Practitioner CertificationSkills
Change ManagementMasters
Job Oriented
45 Hours
Trending
Project Management Master's ProgramUniversity Programs
45 Hours
Trending
Project Management Master's ProgramOn-Demand Courses
PRINCE2 Practitioner CourseRoles
Project ManagerAccreditation Bodies
PMITop Resources
Theories of MotivationCloud Computing
Learn to harness the cloud to deliver computing resources efficiently.
View All Cloud Computing Coursesicon-cloud-snowingCertifications
AWS
32 Hours
Best Seller
AWS Certified Solutions Architect - AssociateAWS
32 Hours
AWS Cloud Practitioner CertificationAWS
24 Hours
AWS DevOps CertificationMicrosoft
16 Hours
Azure Fundamentals CertificationMicrosoft
24 Hours
Best Seller
Azure Administrator CertificationMicrosoft
45 Hours
Recommended
Azure Data Engineer CertificationMicrosoft
32 Hours
Azure Solution Architect CertificationMicrosoft
40 Hours
Azure DevOps CertificationAWS
24 Hours
Systems Operations on AWS Certification TrainingAWS
24 Hours
Developing on AWSMasters
Job Oriented
48 Hours
New
AWS Cloud Architect Masters ProgramBootcamps
Career Kickstarter
100 Hours
Trending
Cloud Engineer BootcampRoles
Cloud EngineerOn-Demand Courses
AWS Certified Developer Associate - Complete GuideAuthorized Partners of
AWSTop Resources
Scrum TutorialIT Service Management
Understand how to plan, design, and optimize IT services efficiently.
View All DevOps Coursesicon-git-commitCertifications
Axelos
16 Hours
Best Seller
ITIL 4 Foundation CertificationAxelos
16 Hours
ITIL Practitioner CertificationPeopleCert
16 Hours
ISO 14001 Foundation CertificationPeopleCert
16 Hours
ISO 20000 CertificationPeopleCert
24 Hours
ISO 27000 Foundation CertificationAxelos
24 Hours
ITIL 4 Specialist: Create, Deliver and Support TrainingAxelos
24 Hours
ITIL 4 Specialist: Drive Stakeholder Value TrainingAxelos
16 Hours
ITIL 4 Strategist Direct, Plan and Improve TrainingOn-Demand Courses
ITIL 4 Specialist: Create, Deliver and Support ExamTop Resources
ITIL Practice TestData Science
Unlock valuable insights from data with advanced analytics.
View All Data Science Coursesicon-dataBootcamps
Job Oriented
6 Months
Trending
Data Science BootcampJob Oriented
289 Hours
Data Engineer BootcampJob Oriented
6 Months
Data Analyst BootcampJob Oriented
288 Hours
New
AI Engineer BootcampSkills
Data Science with PythonRoles
Data ScientistOn-Demand Courses
Data Analysis Using ExcelTop Resources
Machine Learning TutorialDevOps
Automate and streamline the delivery of products and services.
View All DevOps Coursesicon-terminal-squareCertifications
DevOps Institute
16 Hours
Best Seller
DevOps Foundation CertificationCNCF
32 Hours
New
Certified Kubernetes AdministratorDevops Institute
16 Hours
Devops LeaderSkills
KubernetesRoles
DevOps EngineerOn-Demand Courses
CI/CD with Jenkins XGlobal Accreditations
DevOps InstituteTop Resources
Top DevOps ProjectsBI And Visualization
Understand how to transform data into actionable, measurable insights.
View All BI And Visualization Coursesicon-microscopeBI and Visualization Tools
Certification
24 Hours
Recommended
Tableau CertificationCertification
24 Hours
Data Visualization with Tableau CertificationMicrosoft
24 Hours
Best Seller
Microsoft Power BI CertificationTIBCO
36 Hours
TIBCO Spotfire TrainingCertification
30 Hours
Data Visualization with QlikView CertificationCertification
16 Hours
Sisense BI CertificationOn-Demand Courses
Data Visualization Using Tableau TrainingTop Resources
Python Data Viz LibsCyber Security
Understand how to protect data and systems from threats or disasters.
View All Cyber Security Coursesicon-refresh-cwCertifications
CompTIA
40 Hours
Best Seller
CompTIA Security+EC-Council
40 Hours
Certified Ethical Hacker (CEH v12) CertificationISACA
22 Hours
Certified Information Systems Auditor (CISA) CertificationISACA
40 Hours
Certified Information Security Manager (CISM) Certification(ISC)²
40 Hours
Certified Information Systems Security Professional (CISSP)(ISC)²
40 Hours
Certified Cloud Security Professional (CCSP) Certification16 Hours
Certified Information Privacy Professional - Europe (CIPP-E) CertificationISACA
16 Hours
COBIT5 Foundation16 Hours
Payment Card Industry Security Standards (PCI-DSS) CertificationOn-Demand Courses
CISSPTop Resources
Laptops for IT SecurityWeb Development
Learn to create user-friendly, fast, and dynamic web applications.
View All Web Development Coursesicon-codeBootcamps
Career Kickstarter
6 Months
Best Seller
Full-Stack Developer BootcampJob Oriented
3 Months
Best Seller
UI/UX Design BootcampEnterprise Recommended
6 Months
Java Full Stack Developer BootcampCareer Kickstarter
490+ Hours
Front-End Development BootcampCareer Accelerator
4 Months
Backend Development Bootcamp (Node JS)Skills
ReactOn-Demand Courses
Angular TrainingTop Resources
Top HTML ProjectsBlockchain
Understand how transactions and databases work in blockchain technology.
View All Blockchain Coursesicon-stop-squareBlockchain Certifications
40 Hours
Blockchain Professional Certification32 Hours
Blockchain Solutions Architect Certification32 Hours
Blockchain Security Engineer Certification24 Hours
Blockchain Quality Engineer Certification5+ Hours
Blockchain 101 CertificationOn-Demand Courses
NFT Essentials 101: A Beginner's GuideTop Resources
Blockchain Interview QsProgramming
Learn to code efficiently and design software that solves problems.
View All Programming Coursesicon-codeSkills
Python CertificationInterview Prep
Career Accelerator
3 Months
Software Engineer Interview PrepOn-Demand Courses
Data Structures and Algorithms with JavaScriptTop Resources
Python TutorialExpress is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications.
Go to Express.JS and explore for more information to know about express. This site has some links to API, express-generator, Guide with some examples. We will be going to cover some of the topics, which will help you to build a better application using express. Also in express.js site, there are advanced topics like template engines, process managers, security and performance with some best practices. Finally, resources are a great place to known and ask for questions.
Let us start with the course which will cover some of the topics like routes, template engine, middleware, body parsing, cookies, authentication etc. This would be good enough to build an express application.
Brand new express application from scratch:
Install express using npm install express –g for globally for the terminal.
Open your IDE which has terminally inbuilt in it like visual studio code. Create a folder express-app which will have all the examples we are going to work on.
Type ‘npm init’ in terminal to generator the package.json which will prompt a few things like version, description and so on. For now, we can continue with default ones.
If you switch to explorer, package.json is generated and open it to see the values are generated.
Now let's install few dependency i.e. npm install –save express nodemon (to watch and refresh server without restarting it)
Since we will code in ES6 syntax, we need to install compilers for conversation.
npm install –save-dev babel-cli babel-preset-evn babel-stage-0
Check the dependencies and dev-dependencies in package.json to make sure they are installed and segregated accordingly.
Now we want to change the scripts section to add a start which will be used to start our server.
“start” : nodemon ./index.js –exec babel-node –e js
Add babel configuration inside a new file .babelrc as shown below to run our ES6 code to compatible code in server
{ “presets”: [“env”, “stage-0”] }
Finally, we need to create an index.js file which we used in start script of package.json. We can name it differently but the same should be used in package.json.
Section 1:[index.js]
Import express from ‘express’;
const app = express();
const port = 3000;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
Run npm start in the terminal and observe that server is running.
Note: To get mock data in json, we can use Mockaroo which we are going to serve from the server.
Section 2: Let's extend the express app to add data to the server.
- Create a new folder ‘data’ and create a data.json with around 25 records of mock data.
- In Index.js file, import this data
import data from './data/data.json'
- Under the console.log in the callback of app.listen, lets console.log this data.
console.log(data);
- If you haven’t stopped the server, you will see the data in the console.log as nodemon is refreshing it on saving.
- If you run localhost:3000, you will see that data is not sent to the front end, they are still in server.
Section 3: Creating a route, which is responsible for getting your page or data requested from the server. There are basically four methods GET, POST, DELETE and PUT. It follows a request-response paradigm.
- When we type in localhost:3000 in a browser, we see ‘Cannot Get /’ displayed because the default route is Get command.
- Lets add the route for ‘/’.
app.get('/', (req, res) =>
// get data first
res.send(`get request called on PORT: ${PORT}`);
);
- Test in a browser and observe that a response has been displayed in the browser.
- Similarly we can do same for other methods i.e POST, PUT and DELETE.
app.post('/newItem', (req, res) =>
// get data first
res.send(`post request called on PORT: ${PORT}`);
);
app.put('/item', (req, res) =>
// get data first
res.send(`put request called on PORT: ${PORT}`);
);
app.delete('/item', (req, res) =>
// get data first
res.send(`delete request called on PORT: ${PORT}`);
);
- We can test this method using POSTMAN.
- Select POST method and type localhost:3000/newItem -> Click Send
- Select PUT method and type localhost:3000/item -> Click Send
- Select DELETE method and type localhost:3000/item -> Click Send
Note: We can insert body via POST Man and another cool feature of the postman is ‘code’ option. We get the API calling in our preferred language.
Section 4: Now instead of sending a simple text, let us send some data actually.
- Replace the string with data we had from data.json file. Normally, we make a DB call and return the response.
app.get('/', (req, res) =>
// get data first
res.json(data)
);
- Test the same in a post and observe that data is displayed. The same thing can be viewed from the browser as well.
- So basically, we can use any of the front modules like react to build a useful view.
Section 5: Some times, we need to serve some static files like CSS, HTML, images etc.
- Create a new folder ‘Images’ and copy the images from your pictures folder [for windows - Libraries\Pictures].
- Here we are going to use express.static inbuilt method to add a static path to the server.
app.use(express.static('public'));
For now, think that ‘use’ is a method that allows adding specific middleware.
- ‘Use’ method basically takes the first argument as the route and if it is not provided then it would correspond to the default route ‘/’.
- Check and add some files to a public folder, for now, an image. Now switch to the browser and enter localhost:3000/[file name in public folder]. The browser should display that image.
- Similarly we can provide images as static
And app.use('/images', express.static('images'));
- Now browser to localhost:3000/images/[imageName] and should display that image.
This is the complete code till this point:
importexpressfrom'express';
importdatafrom'./data/data.json';
constapp = express();
constPORT = 3000;
// This is for the public folder on path /
app.use(express.static('public'));
// this is for images folder on path images
app.use('/images', express.static('images'));
app.get('/', (req, res) =>
// get data first
res.json(data)
);
app.post('/newItem', (req, res) =>
res.send(`post request called on PORT: ${PORT}`);
);
app.put('/item', (req, res) =>
res.send(`put request called on PORT: ${PORT}`);
);
app.delete('/item', (req, res) =>
res.send(`delete request called on PORT: ${PORT}`);
);
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
console.log(data);
});
Section 6: Route parameters
Till now, we played around with routes without parameters. Now we will extend this example to consider routing parameters.
- Try to get an item by id from the mock data, for which we need to provide a route with path item and id as parameter.
app.get('/item/:id', (req, res, next) => {
// extract the parameters and all parameter are converted to string
console.log(req.params.id);
// Conversation to number
let user = Number(req.params.id);
console.log(user);
// retrieve the specific user based on id from out mockData.
console.log(data[user]);
res.send(data[user]);
});
- Now test by entering localhost:3000/item/04 and see that corresponding data is retrieved by comparing with the data in data.JSON file.
- The same thing can be observed in the terminal because of the console.log.
- We can also send multiple parameters like say we want to categorize the item further like ‘item/:category/:id’.
Route Handlers:
- We have been using Route handler all this time without knowing it. The code gets called inside the callback is called route handler.
app.put('/item', (req, res) =>
res.send(`put request called on PORT: ${PORT}`);
);
- Imagine if you want to handle multiple route handlers in a single route. For this, in express, we have something called next which is 3rd argument used above.
- For the same route of ‘item/:id’, lets add another handler.
app.get('/item/:id', (req, res, next) => {
… //previous code
next();
}, (req, res) => {
console.log(‘Data is returned’);
});
- ‘next’ should always be called when we work using middleware otherwise the request is not processed further.
- Navigate to the same URL to get the specific item and observe data is displayed in the browser.
- Also, look into the terminal to see data is returned to acknowledge that an extended route handler is called.
app.get('/item/:id', (req, res, next) => {
console.log(req.params.id);
letuser = Number(req.params.id);
console.log(user);
console.log(data[user]);
res.send(data[user]);
next();
}, (req, res) =>
console.log('Did you get the right data?')
);
We have a few common methods on the response object which we need to understand before using them. For example, till this point we used res.send and res.json to return the data from the server. It is important to understand the difference.
For other methods refer to the response methods here.
Sometimes we need to have different methods for the same route like app.get(‘/item’), app.put(‘/item’) and app.delete(‘/item’). We can chain all of this together as shown below:
app.route('/item')
.get((req, res) => {
res.send(`a get request with /item route on port ${PORT}`)
})
.put((req, res) =>
res.send(`a put request with /item route on port ${PORT}`)
)
.delete((req, res) =>
res.send(`a delete request with /item route on port ${PORT}`)
);
We are using the app.route method to create chainable route handlers for a route path.
Template engines: Express provides support to a lot of template engines ‘out-of-box’. We can refer to them here.
Out of this, some of the most popular are Pug, hbs, ejs. Let’s compare hbs and pugs.
Hbs – syntax is similar to html template just that variables are in double curly braces.
<div class=’entry’>
<h 1>{{title}}</h 1>
</div>
Pub (jade) – is kind of new syntax and uses white space for differentiation. It is lot smaller.
.entry
h1=title
Let us take any of the above examples and implement templates.
- First we need to set the ‘view engine’ with our interested template engine say pub.
const express = require('express');
const path = require('path');
const app = express();
app.set(‘view engine’, ‘pug’);
- Now express will take care rest but we need to say where it has to look for templates.
- Create a new folder called ‘views’ and set it as views to look for.
app.set(‘views’, path.join(__dirname, ‘./views’));
- Since we have given folder path, express assumes that index file exists and loads it accordingly.
- Let us create an index.pug file and add some basic html content.
doctype html
html
head
body
h1 Index Page
p This is the index page
- Now the route has to know that it has to render this page accordingly.
app.get(‘/’, (req, res, next) => {
return res.render(‘index’);
});
- Start the server and observe that the template is rendered correctly. Now, look into the HTML generated using developer tools, which is optimized by removing white spaces.
- If we want to generate the html in a readable format, we can enable a flag for development environment only.
app.locals.pretty = true;
- res.locals is an object where we can add new fields in specific route and use them in the *.pug file. To illustrate this, let’s use a middleware to listen to error.
app.use((err, req, res, next) => {
res.locals.message = err.message;
const status = err.status || 500;
res.locals.status = status;
res.locals.error = err;
res.status(status);
return res.render('error');
});
- Update the *.pug file to display error message if error occurs.
[we can convert an existing error page to pug format through some of the online converters]
doctype html
html
head
body
h1 Index Page
p This is the index page
if (error)
h1.mr-3.pr-3.align-top.border-right.inline-block.align-content-center=status
.inline-block.align-middle
h2#desc.font-weight-normal.lead=message
pre=error.stack
constexpress = require('express');
constcreateError = require('http-errors');
constpath = require('path');
constapp = express();
app.set('view engine', 'pug');
app.locals.pretty = true;
app.set('views', path.join(__dirname, './views'));
app.get('/', (req, res, next) => {
returnres.render('index');
});
app.use((req, res, next) => {
returnnext(createError(404, 'File not found'));
});
app.use((err, req, res, next) => {
res.locals.message = err.message;
conststatus = err.status || 500;
res.locals.status = status;
res.locals.error = req.app.get('env') === 'development' ? err : {};
res.status(status);
returnres.render('error');
});
app.listen(3000);