Beginners Guide to Express

You don’t have access to this lesson
Please register or sign in to access the course content.

Introduction and Installation

Express is a Node.js web application framework that provides a robust set of features for web applications. Despite being a framework itself, there are many other frameworks based on it. Some of the famous ones are:

  • ItemsAPI: Search backend for web and mobile applications built on Express and Elasticsearch.
  • Kraken: Secure and scalable layer that extends Express by providing structure and convention.
  • LoopBack: Highly-extensible, open-source **Node.js**Node.js® is a JavaScript runtime built on Chrome’s V8 JavaScript engine framework for quickly creating dynamic end-to-end REST APIs.
  • Sails: MVC framework for **Node.js**Node.js® is a JavaScript runtime built on Chrome’s V8 JavaScript engine for building practical, production-ready apps.
  • Hydra-Express: Hydra-Express is a light-weight library which facilitates building **Node.js**Node.js® is a JavaScript runtime built on Chrome’s V8 JavaScript engine Microservices using ExpressJS.
  • graphql-yoga: Fully-featured, yet simple and lightweight GraphQL server.
  • Express Gateway: Fully-featured and extensible API Gateway using Express as foundation.
  • NestJs: A progressive **Node.js**Node.js® is a JavaScript runtime built on Chrome’s V8 JavaScript engine framework for building efficient, scalable, and enterprise-grade server-side applications on top of TypeScript & JavaScript (ES6, ES7, ES8).

Installation

## initializing a node application
$ mkdir express-starter && cd express-starter
$ npm init -y

## installing express package
$ npm i express

## creating index.js
touch index.js
const express = require("express")
const PORT = 3000;
const app = express();

app.get("/", (req, res) => {
	res.send("Hello World")
})

app.listen(PORT, () => console.log(`Express Server Started at port ${PORT}`));

inside file: index.hs

Starting the application

$ node index.js

Open any web browser at the given link : http://localhost:3000

Request and Response

What are request and response?

In computer science, request–response or request–reply is one of the basic methods computers use to communicate with each other in a network, in which the first computer sends a request for some data and the second responds to the request. More specifically, it is a message exchange pattern in which a requester sends a request message to a replier system, which receives and processes the request, ultimately returning a message in response. It is analogous to a telephone call, in which the caller must wait for the recipient to pick up before anything can be discussed. This is a simple but powerful messaging pattern which allows two applications to have a two-way conversation with one another over a channel; it is especially common in client–server architectures. Where client requests and the server responds.

Request in Express

Following shows the properties present inside request object in Express

req.body

// posted data {"email": "hello@hello.com", "password": "P@ssw0rd"}

app.post("/login", (req, res) => {
  const { email, password } = req.body; // req.body contains all posted data
});

req.path

app.get("/". (req, res)=> {
 console.log(req.path) // gives path of the requested url
});

req.param

app.get("/:id", (req, res) => {
  console.log(req.param.id); // contains the data that is in /:id
});

req.query

// the query param sent <http://localhost:3000/?name=ramesh&age=10>

app.get("/", (req, res) => {
  console.log("name:", req.query.name, "age:", req.query.age);
});

The above are the mostly used functions of express request object.

Response in Express

Following shows the properties present inside response object in Express

res.status

app.get("/", (req, res) => {
  res.status(200).end(); // sends 200 response code back to the user 
});

res.render

render views like HTML to the client

app.get("/", (req, res) => {
  res.render("index");
});

res.send

sends data back to the client

app.get("/", (req, res) => {
  res.send("Hello");
});

res.type

It sets the content-type of HTTP header

app.get("/", (req, res) => {
	res.type('application/json');
  res.status(200).send({"message": "Hello"});
});

res.json

Returns JSON as body type

app.get("/", (req, res) => {
	res.type('application/json');
  res.json({message: "Hello"});
});

res.cookie

Setting cookie

app.get("/", (req, res) => {
	res.cookie('user', {token: '213yohl1i2j.e4dgbdgquerwbiuibI.hqwordhnsdk'});
});

HTTP METHODS in Express

What is HTTP?

The Hypertext Transfer Protocol (HTTP) is designed to enable communications between clients and servers.

HTTP works as a request-response protocol between a client and server.


HTTP Methods

  • GET
  • POST
  • PUT
  • HEAD
  • DELETE
  • PATCH
  • OPTIONS
  • CONNECT
  • TRACE

The two most common HTTP methods are: GET, POST, PUT, DELETE.

Popular HTTP Methods used in CRUD applications

SnMethodDescription
1GETUsed to get data or resource present in the server
2POSTUsed to create new resource in the server
3PUTUsed to update the present resource in the server
4DELETEUsed to delete resource or data present in the server

Using HTTP Methods with Express

GET

app.get("/", (req, res) => {
	res.send("USED TO RECIEVE RESOURCE FROM THE SERVER");
});

POST

app.post("/", (req, res) => {
	res.send("USED TO SAVE RESOURCE TO THE SERVER");
});

PUT

app.put("/", (req, res) => {
	res.send("USED TO UPDATE RESOURCE PRESENT IN THE SERVER");
});

DELETE

app.delete("/", (req, res) => {
	res.send("USED TO DELETE RESOURCE FROM THE SERVER");
});

Routing in Express

Routing in express

Routing refers to how an application’s endpoints (URIs) respond to client requests. You define routing using methods of the Express app object that correspond to HTTP methods; for example, app.get() to handle GET requests and app.post to handle POST requests.

Different methods of routing in express

1. Method (same file)

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

app.get('/', (req, res) => {
	res.status(200).send("Responds when GET to <http://localhost:3000/> is Done");
});

app.post('/', (req, res) => {
	res.status(200).send("Responds when POST to <http://localhost:3000/> is Done");
});

app.put('/', (req, res) => {
	res.status(200).send("Responds when PUT to <http://localhost:3000/> is Done");
});

app.delete('/', (req, res) => {
	res.status(200).send("Responds when DELETE to <http://localhost:3000/> is Done");
});

app.listen(3000, () => console.log("SERVER STARTED AT PORT 3000"));

Here all the routes are present inside the same file.

2. Method (separate file)

const router = require("express").Router();

router.get('/', (req, res) => {
	res.status(200).send("Responds when GET to <http://localhost:3000/> is Done");
});

router.post('/', (req, res) => {
	res.status(200).send("Responds when POST to <http://localhost:3000/> is Done");
});

router.put('/', (req, res) => {
	res.status(200).send("Responds when PUT to <http://localhost:3000/> is Done");
});

router.delete('/', (req, res) => {
	res.status(200).send("Responds when DELETE to <http://localhost:3000/> is Done");
});

module.exports = router;

File: routes.js

const routes = require("./routes.js");
const express = require("express");
const app = express();

app.use("/", routes);   // Gets all routes from routes.js file

app.listen(3000, () => console.log("SERVER STARTED AT PORT 3000"));

File: index.js

By following this architecture there is separation of concerns routes can go on their own folder and when time comes they can be used by app.use() method.

Middleware in Express

What are middlewares and How do they work?

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.

Middleware functions can perform the following tasks:

  • Execute any code.
  • Make changes to the request and the response objects.
  • End the request-response cycle.
  • Call the next middleware function in the stack.

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.

Writing a middleware in express.

//* Creating Middleware
function userVerify (req, res, next) {
	const { email, password } = req.body;

	if(email != "hello@hello.com" && password != "P@ssw0rd") {
    res.send("Login Failed email or password incorrect");
  }
  next();
}

//* Using Middleware
app.post("/login", userVerify, (req, res) => {
	res.send("User Login Successful");
});

The above function checks if the email and password are correct if they are correct then next() function is called, and it goes to the app.post otherwise it returns login failed from userVerify() middleware.

Conclusion

In this chapter, we’ve saw a overview to express framework, and how it works with sample examples.