Express Slides
Express Slides
js
1
When it comes to build web applications using Node.js, creating a server can take a lot of time. Over the years Node.js has
matured enough due to the support from community. Using Node.js as a backend for web applications and websites help the
developers to start working on their application or product quickly.
2
What is Express?
Express is the most popular Node.js framework because it requires minimum setup to start an application or an API and is
fast and unopinionated at the same time.
Express was developed by TJ Holowaychuk and is now maintained by Node.js foundation and open source developers.
Express is minimal because it does not come loaded with all sorts of functionality, which makes it a bloat-free framework.
Out of the box, it supports only the very basic features of a web framework. Even the supported features are not all
enabled by default, you have the option to pick and use, according to your needs.
The flexibility in Express comes from the use of middlewares and Node modules. Express middlewares and Node modules
are pluggable JavaScript components, which make Express apps very modular, flexible, and extensible.
Express is a powerful framework because it gives you complete access to the core Node APIs. Anything you can do with
Node, you can do it with Express too.
3
The story of Express
Node in 2009 was released and was very well received by the web development community, and it started to grow very
rapidly in popularity.
Apart from being a general-purpose software development platform, Node provided a web server API (Application
Programming Interface), using which developers could create web apps using JavaScript as the backend programming
language.
However, there was a problem with Node's web server API: It was a little too low level, and you had to write and re-write
many of the web server functions in your web apps.
Within five months of Node's release, in June 2009, T.J. Holowaychuk, released an open source project named Express to
make web development a little easier in Node. Express was inspired by Ruby's Sinatra and built on top of Node's web
server API.
In June 2010, Sencha, under its Sencha Labs, started an open source project named Connect, to solve the modularity and
extensibility issue in the Node web server API. The project was inspired by Ruby's Rack web server interface. Tim Caswell, a
Sencha employee, and T.J. Holowaychuk, were roped in to lead the project.
4
The story of Express
Like Express, Connect was also built on top of Node's web server API, and came with a middleware system, which allowed
small re-usable programs to be plugged onto it to handle HTTP-specific functionalities. Connect middlewares took care of
many of the commonly required functionalities in web apps for Node. On top of that, anyone could write their own
middleware for their apps.
By now, there were two different web development frameworks for Node: Express and Connect—one was inspired by
Sinatra, and the other by Rack. This caused a bit of confusion in the Node community, especially with Holowaychuk
working on both of them.
But as luck would have it, it became obvious that Express and Connect were actually complementary frameworks. So, in
July 2010, Holowaychuk decided to re-architect Express to run on top of Connect, effectively merging Connect with
Express to create a new incarnation of Express in v1.0.0.
With Express v1.0.0, there was no more confusion about which web development framework to choose in Node. Express
was Connect with additional functionalities built on top of it. To this day it remains the same—Express continues to use the
Connect middleware, and any change in Connect is invariably reflected in Express.
5
Why use Express ?
Express lets you build single page, multi-page, and hybrid web and mobile applications. Other common backend use is to
provide an API for a client (whether web or mobile).
It comes with a default template engine, Jade which helps to facilitate the flow of data into a website structure and does
support other template engines.
It supports MVC (Model-View-Controller), a very common architecture to design web applications.
It is cross-platform and is not limited to any particular operating system.
It leverages upon Node.js single threaded and asynchronous model.
6
What can we make with Express ?
Building server sided applications:
APIs
Saving data to a DB
Schedule cron jobs
Real time applications
7
Setup and installation
We start by creating the configuration file using npm init -y
In package.json
{
"name": "expressjs",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "node ./src/index.js",
"start:dev": "nodemon ./src/index.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.18.2"
}
8
}
Setting the server
const express = require("express");
app.listen(PORT, () => {
console.log(`Running Express server on port ${PORT}`);
});
Because we havent implemented any route to handle requests, we only opened the port for communication.
9
Get request
Get some kind of resource from the server.
Request parameter: gives you all the information about the request ( cookies, ip address, headers ... )
10
Response methods
The methods on the response object (res) in the following table can send a response to the client, and terminate the request-
response cycle. If none of these methods are called from a route handler, the client request will be left hanging.
Method Description
res.sendStatus() Set the response status code and send its string representation as the response body.
11
Post request
Creating a resource
When it comes to post requests we should send back a status code of 201 => creation of a record has been made successfully
12
Post request
For the server to properly interpret or parse the data sent in the resquest body we need to use a middleware (It is a function
that is invoced in the middle of two main functionalities).
app.use(express.json());
app.use(express.urlencoded());
13
Post request
app.post("/groceries", (req, res) => {
console.log(req.body);
groceryList.push(req.body);
res.sendStatus(201);
});
14
Middlewares
Express is a routing and middleware web framework that has minimal functionality of its own: An Express application is
essentially a series of middleware function calls.
Middleware functions are functions that have access to the request object (req), the response object (res), and the next
middleware function in the application’s request-response cycle. The next middleware function is commonly denoted by a
variable named next.
If the current middleware function does not end the request-response cycle, it must call next() to pass control to the
next middleware function. Otherwise, the request will be left hanging.
15
Middlewares
app.get("/groceries",
(req, res) => { console.log("Inside our middleware"); },
(req, res) => { res.send(groceryList); }
);
Nothing is getting send because we are still stuck in the middleware that we created. we need the next() function to go to
the next middleware!
app.get("/groceries",
(req, res, next ) => { console.log("Inside our middleware");
next(); },
(req, res) => { res.send(groceryList); }
);
16
Middlewares
To apply a middleware globaly:
17
Routers
Route parameters
Route parameters are named URL segments that are used to capture the values specified at their position in the URL. The
captured values are populated in the req.params object, with the name of the route parameter specified in the path as their
respective keys.
The app will now be able to handle requests to /birds and /birds/about, as well as call the timeLog middleware function that is 19
specific to the route.
Query parameters
In simple terms, a query string is the part of a URL after the question mark (?). It is meant to send small amounts of information
to the server via the URL. This information is usually used as parameters to query a database, or maybe to filter results. It's
really up to you what they're used for.
Example: https://blabla.com/?page=2&limit=3
The query parameters are the actual key-value pairs like page and limit with values of 2 and 3, respectively.
In the example above, we assume the page and limit parameters always exist. If neither of these parameters are given in
the URL, we'd receive undefined for both page and limit instead.
20
Cookies
Cookies are small files of information that a web server generates and sends to a web browser. Web browsers store the cookies
they receive for a predetermined period of time, or for the length of a user's session on a website. They attach the relevant
cookies to any future requests the user makes of the web server.
21
Cookies
To access the cookies, we use the cookie-parser package first by installing it and then use it as a middleware.
22
Sessions
Cookies are client-side files on a local computer that hold user information. Sessions are server-side files that contain user data.
23
Sessions
router.post("/shopping/cart/item", (request, response) => {
const { item, quantity } = request.body;
const cartItem = { item, quantity };
const { cart } = request.session;
//console.log(cartItem);
if (cart) {
request.session.cart.items.push(cartItem);
} else {
request.session.cart = {
items: [cartItem],
};
}
response.sendStatus(201);
});
The moment the POST request is sent a cookies with a session ID is created
24
Sessions
router.get("/shopping/cart", (req, res) => {
const { cart } = req.session;
if (!cart) {
res.send("You have no items on your cart");
} else {
res.send(cart);
}
});
25
Exercise:
Create two routers:
26
Data Storage
When it comes to building robust and scalable applications in Node.js, mastering data storage and management is crucial. Data
lies at the heart of every application, and how effectively we handle and store it can make all the difference in the performance
and scalability of our Node.js projects.
27
Mongoose for MongoDB
Mongoose is a javascript library that allows to make a connection to a mongodb server aswell as interact with database.
npm i mongoose
// getting-started.js
const mongoose = require('mongoose');
28
MongoDB Schemas
A schema is a JSON object that defines the structure and contents of your data. Schemas represent types of data rather than
specific values. These include primitives, like strings and numbers, as well as structural types, like objects and arrays, which you
can combine to create schemas that represent custom object types.
29
module.exports = mongoose.model("users", UserSchema);
Records manipulation
Creating a record
// or
Querying
Deleting
Updating
31
ExpressJS - Templating
Pug is a templating engine for Express. Templating engines are used to remove the cluttering of our server code with HTML,
concatenating strings wildly to existing HTML templates.
To use Pug with Express, we need to install it: npm install --save pug ,
Now that Pug is installed, set it as the templating engine for your app. You don't need to 'require' it. Add the following code to
your index.js file.
Now create a new directory called views. Inside that create a file called first_view.pug, and enter the following data in it.
doctype html
html
head
title = "Hello Pug"
body
p.greetings#people Hello World!
32
ExpressJS - Templating
To run this page, add the following route to your app:
html
html
head
title Form Tester
body
form(action = "/", method = "POST")
div
label(for = "say") Say:
input(name = "say" value = "Hi")
br
div
label(for = "to") To:
input(name = "to" value = "Express forms")
br
33
button(type = "submit") Send my greetings
TP2: Putting everything together
Create a registration and authentication web page using Pug
The user's information should be stored in mongoDB
Use passport.js for handling authentication
After authenticating successfully redirect to the books page
The books are stored in a local variable
The books page should not be accessible unless the user is authenticated
Use Tailwind CSS to handle the styling part of the application
34