How Express JS Works Explained

Understand Express.js Flow


Require Express

const express = require("express");

We use require("express") to include the Express module.

Why we can’t use Express directly?

Because Express returns a function. To use it, we need to call it:

const app = express();


Alternatively, you can do it like this in one line:

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

This creates an Express application and stores it in the app variable.


Start the Server

app.listen(3200);

This tells Express to start a server on port 3200.


Check app Object

If you want to inspect what’s inside the Express app, use:

console.log(app);

This will show all the available methods and properties of the Express app.


Express.js Routes and Flow

Basic Route Example

app.get("", (req, resp) => {
resp.send("<h1>Home Page</h1>");
});
  1. .get() is used to handle GET requests.
  2. It takes two parameters: a path ("" or "/about") and a callback function.


Multiple Routes Example

app.get("", (req, resp) => {
resp.send("<h1>Home Page</h1>");
});

app.get("about", (req, resp) => {
resp.send("<h1>About Page</h1>");
});

app.get("/", (req, resp) => {
resp.send("<h1>Home Page 2</h1>");
});

Note:

Express matches and executes the first matching route. So if "" and "/" look similar, only the first one is executed.