Express.js Introduction
# Express.js Introduction
Welcome to Chapter 13! You survived the raw Node.js modules. You've seen how tedious it is to build a server using http.createServer, manually parse URLs with if/else statements, and manually set HTTP headers.
In the real world, virtually nobody does that. We use Express.js. Express is a fast, unopinionated, minimalist web framework built *on top* of the Node.js http module. It does all the heavy lifting for you.
---
1. Introduction
If Node.js is the engine of a car, Express.js is the steering wheel, the pedals, and the dashboard. It makes driving the car infinitely easier.
Express is an NPM package. It abstracts away the complex, repetitive code required to set up a server and handle routing. It is the "E" in the famous MERN stack (MongoDB, Express, React, Node) and MEAN stack.
---
2. Learning Objectives
By the end of this chapter, you will be able to:
- Install Express.js using NPM.
- Instantiate an Express application.
- Create a basic server that listens on a port.
- Define simple GET routes using Express syntax.
-
Understand how Express simplifies the
reqandresobjects.
---
3. Beginner-Friendly Explanations
What does "Framework" mean?
A library (likedate-fns) is a tool you call when you need it.
A framework dictates how you structure your entire app. Express provides a structured way to handle incoming requests, route them to the correct code, and send responses easily.
The Express Way vs The Raw Way
Raw Node:Express.js:
Look how clean that is! res.send() is a magical Express method that automatically figures out you are sending HTML, sets the status to 200, sets the Content-Type, and ends the response for you.
---
4. Syntax Explanation
Let's look at the absolute minimum code required to start an Express server.
```javascript id="ch13-syntax-1" // 1. Require the express package const express = require('express');
// 2. Create the express application instance (traditionally named 'app') const app = express();
// 3. Define a route (When a user visits the root '/') app.get('/', (req, res) => { res.send('Hello from Express!'); });
// 4. Start the server app.listen(3000, () => { console.log('Express server is running on port 3000'); });
bash id="ch13-bash-1" npm init -y npm install express
javascript id="ch13-code-1" const express = require('express'); const app = express();
app.get('/api/user', (req, res) => { const user = { name: "Alice", role: "Admin", age: 25 }; // Express automatically converts the object to a JSON string // and sets Content-Type to application/json res.json(user); });
app.listen(3000);
javascript id="ch13-code-2" const express = require('express'); const app = express();
app.get('/', (req, res) => res.send('Home Page')); app.get('/about', (req, res) => res.send('About Page'));
// 404 Handler (MUST be placed after all other routes) app.use((req, res) => { // Chain status() and send() together res.status(404).send('<h1>404 - Sorry, page not found!</h1>'); });
app.listen(3000);
bash mkdir express-starter cd express-starter npm init -y npm install express npm install -D nodemon
json "scripts": { "start": "node app.js", "dev": "nodemon app.js" }
javascript id="ch13-mini-project" // app.js const express = require('express'); const app = express(); const PORT = 3000;
// Home Route
app.get('/', (req, res) => {
res.send(
<h1>Welcome to Express!</h1>
<p>Try visiting <a href="/api/info">/api/info</a></p>
);
});
// API Route returning JSON app.get('/api/info', (req, res) => { res.json({ framework: "Express.js", version: "4.x", status: "Active" }); });
// 404 Route app.use((req, res) => { res.status(404).json({ error: "Route not found" }); });
// Start Server
app.listen(PORT, () => {
console.log(🚀 Express Server running on http://localhost:${PORT});
});
``
Run it:
npm run dev
---
12. Coding Challenges
Challenge 1: Create a route /random that generates a random number between 1 and 100 and sends it back to the client as an HTML <h1> tag.
Challenge 2: Look up the res.redirect() method in the Express documentation. Create a route /google that automatically redirects the user to https://www.google.com.
---
13. MCQs with Answers
Q1: What is Express.js? A) A database management system. B) A new programming language. C) A fast, minimalist web framework for Node.js. D) A built-in core Node module. Answer: C
Q2: Which method is used to send a JavaScript object back to the client as JSON?
A) res.sendObject()
B) res.json()
C) res.end()
D) res.write()
Answer: B
Q3: Why is res.send() better than the raw res.end()?
A) It executes faster.
B) It automatically sets the Content-Type header and status codes.
C) It compresses the data.
D) It prevents server crashes.
Answer: B
Q4: Where should the 404 Not Found handler be placed in an Express file?
A) At the very top.
B) Inside the app.listen callback.
C) At the very bottom, after all other routes.
D) It doesn't matter.
Answer: C
---
14. Interview Questions
- 1. Why use Express instead of the built-in HTTP module?
, app.post) and helpful response methods (res.json, res.sendFile), vastly speeding up development.
-
2.
What does
res.json() do under the hood?
*Answer:* It converts the provided JavaScript object or array into a JSON string using JSON.stringify(), sets the Content-Type header to application/json, and then calls res.send() to transmit the data.
---
15. FAQs
Q: Do I have to use Express?
A: No, there are other frameworks like Fastify, Koa, and NestJS. However, Express is the industry standard and has the largest community, making it the perfect framework to learn first.
Q: Is Express frontend or backend?
A: Strictly Backend. It runs on the server and listens for requests coming from the frontend.
---
16. Summary
-
Express.js is a third-party NPM package that simplifies building web servers.
-
Instantiate an app using
const app = express().
-
Define routes simply using methods like
app.get('/path', callback).
-
Use
res.send() for HTML/text, and res.json() for APIs.
-
Express evaluates routes from top to bottom, making a bottom
app.use perfect for 404 errors.
---
17. Next Chapter Recommendation
We've only touched
GET` requests so far. What happens when a user submits a form or tries to log in? In Chapter 14: Express.js Routing, we will dive deeper into advanced routing, POST requests, and dynamic route parameters!