Node.js Introduction to Express.js
Express.js (commonly called Express) is the most popular web framework for Node.js. It is a minimal, flexible, and fast framework that simplifies the process of building web servers, APIs, and web applications on top of Node.js's built-in http module.
While Node.js's http module can create servers, it requires a lot of manual work to handle routing, parsing request bodies, setting headers, and managing responses. Express provides a clean, structured way to do all of this with far less code.
Why Use Express Instead of Just http?
Consider the difference: without Express, routing alone requires manually checking req.url and req.method with many if/else statements. Express provides a simple, organized routing system that handles this elegantly. Express also provides:
- Clean routing for different URLs and HTTP methods.
- Middleware support for processing requests in layers.
- Built-in support for JSON and form data.
- Template engine integration (EJS, Handlebars, Pug).
- A large ecosystem of compatible middleware packages.
Installing Express
First, set up a project with a package.json file:
mkdir my-express-app
cd my-express-app
npm init -y
Then install Express:
npm install express
Creating the First Express Server
// app.js
const express = require('express');
const app = express();
const PORT = 3000;
// Define a route for the home page
app.get('/', function(req, res) {
res.send('Welcome to my first Express server!');
});
// Start the server
app.listen(PORT, function() {
console.log('Server is running at http://localhost:' + PORT);
});
Run with:
node app.js
Visit http://localhost:3000 in a browser. The page displays:
Welcome to my first Express server!
Compare this to the same functionality using just the http module — Express requires significantly less code and is far more readable.
Understanding the Express Application Object
When express() is called, it returns an application object (commonly named app). This object is used for everything:
- Defining routes (
app.get(),app.post(), etc.) - Adding middleware (
app.use()) - Starting the server (
app.listen()) - Configuring settings (
app.set())
Sending Different Types of Responses
Sending a Plain Text Response
app.get('/text', function(req, res) {
res.send('This is plain text.');
});
Sending a JSON Response
app.get('/json', function(req, res) {
res.json({ name: 'Alice', role: 'admin', active: true });
});
Using res.json() automatically sets the Content-Type header to application/json and converts the object.
Sending an HTML Response
app.get('/html', function(req, res) {
res.send('<h1>Hello from Express!</h1><p>This is HTML content.</p>');
});
Setting a Status Code
app.get('/not-found', function(req, res) {
res.status(404).send('Page not found.');
});
A Complete Basic Express Server with Multiple Routes
const express = require('express');
const app = express();
// Home page
app.get('/', function(req, res) {
res.send('<h1>Home Page</h1>');
});
// About page
app.get('/about', function(req, res) {
res.send('<h1>About Page</h1><p>We build amazing apps.</p>');
});
// API endpoint returning JSON
app.get('/api/status', function(req, res) {
res.json({ status: 'ok', message: 'Server is running' });
});
// 404 handler — must be defined LAST
app.use(function(req, res) {
res.status(404).send('<h1>404 - Route Not Found</h1>');
});
app.listen(3000, function() {
console.log('Express server running at http://localhost:3000');
});
Using nodemon for Auto-Restart During Development
During development, the server must be restarted manually every time code changes. nodemon automates this:
npm install nodemon --save-dev
Add a dev script to package.json:
"scripts": {
"start": "node app.js",
"dev": "nodemon app.js"
}
Now run the server with:
npm run dev
The server automatically restarts whenever a file is saved.
Serving Static Files
Express can serve static files (HTML, CSS, images, JS) from a folder using the built-in express.static() middleware:
const express = require('express');
const path = require('path');
const app = express();
// Serve all files inside the 'public' folder
app.use(express.static(path.join(__dirname, 'public')));
app.listen(3000);
If a file named public/index.html exists, it will be automatically served when visiting http://localhost:3000.
Key Points
- Express is a minimal and flexible Node.js framework for building web servers and APIs.
- Install it with
npm install expressand import it withrequire('express'). express()creates the application object (app) used to define routes, middleware, and start the server.res.send()sends text or HTML;res.json()sends JSON with the correct headers.res.status(code)sets the HTTP status code before sending a response.- The 404 handler using
app.use()must always be the last defined route. - Use
nodemonduring development to automatically restart the server on file changes. express.static()serves static files from a directory without writing individual routes.
