Express.js Mastery / Express: Letโ€™s Start Building The Natours API!

Setting up Express and Basic Routing

๐Ÿ“‚ Project: Natours (Course Main Project)

๐Ÿ”น Step 1: Get the Starter Project

  • โฌ‡๏ธ Download the repo from here course files

  • ๐Ÿ“– Open starter folder from 4-natours

  • ๐Ÿ“ฆ Contains: prettier config, ESLint config (not set up yet โ€” comes later), CSS/images folders, and some data files used later in the section.


๐Ÿ”น Step 2: Create package.json

npm init
  • ๐Ÿท๏ธ Name: natours (must be lowercase, no capital letters allowed by npm).

  • ๐Ÿ”ข Version: 1

  • ๐Ÿ“ Description: e.g. "learning node, express, mongoDB"

  • ๐Ÿ“„ Entry point: app.js (instead of the default index.js)

  • โญ๏ธ Skip test command, git, keywords โ€” fill in author your name or any random name


๐Ÿ”น Step 3: Install Express

npm i express@4
  • ๐Ÿ“ฆ Installs the latest version 4 of Express.

  • โš ๏ธ Important: install version 4, not 5 โ€” version 5 is a major version that could introduce breaking changes (even though not much actually changes).

  • ๐Ÿท๏ธ @4 ensures the latest 4.x.x release (e.g. 4.16.4) โ€” any 4.x version is fine.

  • ๐Ÿ“ This creates the node_modules folder.


๐Ÿ”น Step 4: Create app.js

  • ๐Ÿ“„ Convention: keep all Express configuration/setup in a file called app.js.


๐Ÿ”น Step 5: Import Express and Create the App

const express = require('express');
const app = express();
  • ๐Ÿ“ฅ express is a function โ€” calling it (express()) returns an object (app) with a bunch of built-in methods attached.


๐Ÿ”น Step 6: Start the Server

const port = 3000;

app.listen(port, () => {
  console.log(`App running on port ${port}...`);
});
  • ๐Ÿš€ app.listen() is similar to the http module's .listen() used earlier โ€” Express is 100% Node.js under the hood, just simplified.


๐Ÿ”น Step 7: Define a Basic Route (GET)

app.get('/', (req, res) => {
  res.status(200).send('Hello from the server side');
});
  • ๐Ÿ›ฃ๏ธ Routing = defining how the app responds to a specific URL + HTTP method combination.

  • ๐Ÿ“ฅ app.get(url, callback) โ€” responds to GET requests on that URL.

  • ๐Ÿ“ฆ Callback receives req (request) and res (response) โ€” same concept as plain Node, but Express's req/res objects come with a lot more built-in data and methods.

  • ๐Ÿ”ข res.status(code) sets the HTTP status code โ€” chain it before .send().

  • ๐Ÿ“ค res.send(data) sends a plain string response.


๐Ÿ”น Step 8: Set Up Nodemon

  • Install nodemon as dev dependency: npm i nodemon --save-dev

  • Setup package.json: add starter script

 "scripts": {
    "start": "nodemon app.js"
  },

๐Ÿ”น Step 9: Run the Server

โ€ผ๏ธ Note: You can use nodemon app.js, but npm start is the preferred approach since it's already configured.

npm start
  • โœ… Confirms: "App running on port 3000"


๐Ÿ”น Step 10: Test With Postman

  • ๐Ÿ“ฎ Set the URL to 127.0.0.1:3000 (or localhost:3000), method GET, hit Send.

  • ๐Ÿ“„ Response: Hello from the server side

  • ๐ŸŒ Same result would show in a browser too โ€” Postman is just more convenient for API testing going forward.


๐Ÿ”น Step 11: Send JSON Instead of Plain Text

app.get('/', (req, res) => {
  res
    .status(200)
    .json({ message: 'Hello from the server side!', app: 'Natours' });
});
  • res.json(obj) sends a JSON response instead of res.send().

  • Postman displays it as nicely formatted, color-coded JSON, along with status code, response time, and response size.

  • Changing the status code (e.g. to 404) is as easy as res.status(404) โ€” Postman will reflect that immediately.


๐Ÿ”น Step 12: Test What Happens With an Undefined Route/Method

  • ๐Ÿงช Sending a POST request to / (with only a GET route defined) returns Express's default response:

Cannot POST /
  • โŒ With a 404 status โ€” because no route matches that URL + method combination.


๐Ÿ”น Step 13: Define a Route for POST

app.post('/', (req, res) => {
  res.send('You can post to this endpoint');
});
  • ๐Ÿ“ค Sending POST to / now returns: "You can post to this endpoint" with status 200 (the default status when none is explicitly set).


๐Ÿ”น Step 14: Automatic Headers

  • ๐Ÿท๏ธ Using res.json(...) automatically sets the Content-Type header to application/json.

  • โš™๏ธ Express also automatically adds other headers like X-Powered-By: Express, Date, Connection, etc. (covered in more detail later in the course).


โœ… Key Takeaway

  • ๐Ÿš€ express() creates the app; app.listen() starts the server.

  • ๐Ÿ›ฃ๏ธ Routing in Express = app.<method>(url, callback) โ€” e.g. app.get(), app.post().

  • ๐Ÿ“ค res.send() โ†’ plain text/string response.

  • ๐Ÿ“ฆ res.json() โ†’ JSON response (also auto-sets the correct Content-Type header).

  • ๐Ÿ”ข res.status(code) โ†’ sets the HTTP status code, chainable before .send()/.json().

  • โŒ Undefined route/method combinations automatically get a 404 "Cannot [METHOD] [URL]" response from Express.

  • โšก Compared to raw Node, Express drastically simplifies routing and response handling.