Express.js

All about Express.js


Popular and lightweight web application framework for Node.js that simplifies the process of building robust, scalable and flexible web applications. Express simplifies the implementation of tasks that requires significant effort such HTTP module.

  • What Express provides:

    • Extensions
    • Middleware
    • Routing
    • Views
  • Initialize project with Express

/* Accessing express module */
const express = require("express"); 
/* Initialize express app */
const app = express(); 

HTTP Verbs/Methods

HTTP methods are a set of actions that allow communication between the client (browser) and server, indicating what types of operations the client will perform on the server. Used in RESTful APIs.

  • HTTP GET - get a resource from server. (e.g fetching html page or assets like json, css, images, etc.)

  • HTTP POST - posting or adding a resource on the server.

  • HTTP PUT - updating the whole resource already on the server. (e.g update all fields)

  • HTTP PATCH - partially updates a resource already on the server. (e.g update just one field)

  • HTTP DELETE - delete a resource from the server

Warning

Always return the response to avoid errors and weird bugs.

Request and Response Object

The basic request and response objects have extra functionality.

  • request.ip - ip address
  • request.get - to obtain HTTP headers
  • request.status - to set status code
  • request.send
  • response.redirect - Redirects to a particular site
  • response.sendFile - To send a file
  • response.json - sending JSON response

Middleware 🚧

Middleware are functions that intercepts a request, modify it, and let them continue to next step, or end the request-resposne cycle.

Example:
  • We can intercept the request from user before the response from server. This is useful to authentication, logging, and error handling**.
  • A middleware function can modify the request or response objects
  • In a login page, If a user sends an invalid password, the middleware can intercept this password before sending the request to the Database.
  • If the password is not valid, then the middleware DOES NOT send the response back to the user.
Implementation:

We use the app variable with .use() to add new middlewares

How a middleware looks like? Here are some exmaples:

// Importing Modules
const path = require("path")
const express = require("express")
const flash = require("connect-flash")
const csrf = require("csurf")
// Using these modules
const app = express()
const publicPath = path.resolve(__dirname, "staticFolderName") // Create path same for Linux, Mac, Windows
 
// Middleware to read static file
app.use(express.static(publicPath))
 
// Middleware for Flash messages
app.use(flash())
 
// Middleware to add CSRF protection to our app
app.use(csrf())
 
// Simple Middlewares that uses request and response to display messages
app.use((request, response, next) => {
  console.log("Received: " + request.url);
  message = "First middleware function\n";
  console.log(message);
  next(); /* go to next middleware function, needed if have a next middleware */
});
 
app.use((request, response) => {
  let secondMessage = "Second middleware function";
  console.log(secondMessage);
  message += secondMessage;
  response.end(message);
});
 

Routing 🚏

Routing allows us to associate an URL with an HTTP method.

  • Routes are defined using HTTP methods such as GET, POST, PUT, and DELETE and can be used to handle different types of requests.
  • Routes with method GET are oftenly to display HTML or retrieve data from server.
  • Routes with method POST are oftenly when the HTML has a form and a submit button that changes the server.
  • We no longer use app.use() (this is for middlewares), we use instead app.get(), app.post(), app.put(), etc.
  • A website can have different routes
    • /
    • /register
    • /login
    • /user
    • /user/settings
Example:
  • We can have a route /login with method GET, which retrieve a HTML page (GET response) that has forms necessary to register an user.
  • We can have another route /login with method POST. When user clicks on submit button, the data will be sent to the server, we can get the user inputs with POST request. Returns their user home page (POST response) if login sucessful, otherwise /login page (POST response) if no succesful.
Code:
app.get("/login", (request, response) => {
  response.render("login.html") // renders a html when enters to this route
})
 
app.post("/login", (request, response) => {
  // POST request to get data sent by user then validate
  ..code..
  // POST response to send a html back to the user
  response.render("user.html")
})
 
app.put()
 
app.delete()

Params vs Query vs Body 🆚

req.params

An object containing properties of the URL params. For example, in the route /users/:id, the id parameter can be accessed with req.params.id. These parameters are defined in the route definition using : before the parameter name.

// GET /users/:id
// URL: somewebsite.com/users/123
app.get('/users/:id', (req, res) => {
  const params = req.params; // -> { id: 123 }
  const { id } = params; // -> 123
});

req.query

An object containing each query string parameter from the URL.

Query string params are appended at the end of a URL after a ? character and separated by & character.

For example, in the URL /search?q=term&page=2, the q and page parameters can be accessed with req.query.q and req.query.page, respectively.

// GET /users
// URL: somewebsite.com/users/search?q=term&page=2
app.get('/users', (req, res) => {
  const queryParams = req.query /// -> { q: term , page: 2 }
  const { q, page } = queryParams;
});

req.body

An object containing data submitted by an HTTP request, usually from forms or HTTP POST / PUT.

// Form: name = jose , password = 123
// HTTP POST: axios.post(url, {name:'jose', password:'123'} )
app.post('/users', (req, res) => {
  const extract_body = req.body; // -> { name: jose, password: 123 }
  const name = req.body.name // -> jose
  const password = req.body.password // -> 123
});

Testing Server

We can test our routes to see if they work with curl in the shell command

curl -X GET https://somewebsite.com 
curl -X POST https://somewebsite.com -d "key1=value1&key2=value2"
curl -X DELETE https://somewebsite.com -H "Authorization: Bearer <token>"

However, there is something even more powerful, called PostMan, that allows you to issue HTTP requests.

Lightweight apps similar to Postman:

  • Insomnia
  • Yaak (currently using)
  • Thunder Client (VSCode Extension)