Introduction
Express.js is a lightweight and flexible Node.js framework that simplifies building web applications and APIs. It provides powerful tools for handling routing, middleware, and HTTP requests efficiently.
1. Installing Express.js
Before using Express, install it using npm:
npm install express
To create a basic Express application, require the module:
const express = require("express");
const app = express();
2. Creating a Basic Express Server
Express makes it easy to create an HTTP server.
Example:
const express = require("express");
const app = express();
app.get("/", (req, res) => {
res.send("Hello from Express!");
});
app.listen(3000, () => console.log("Express server running on port 3000"));
Explanation:
.get("/")
handles GET requests to the root URL.res.send()
sends a response.- The server listens on port 3000.
3. Handling Different HTTP Methods
Express allows handling different HTTP methods such as GET
, POST
, PUT
, and DELETE
.
Example:
app.get("/users", (req, res) => {
res.json({ message: "GET request received" });
});
app.post("/users", (req, res) => {
res.json({ message: "POST request received" });
});
app.put("/users/:id", (req, res) => {
res.json({ message: `User ${req.params.id} updated` });
});
app.delete("/users/:id", (req, res) => {
res.json({ message: `User ${req.params.id} deleted` });
});
4. Middleware in Express
Middleware functions are executed during request processing. They can be used for logging, authentication, and modifying request objects.
Using Middleware
app.use((req, res, next) => {
console.log(`${req.method} request received at ${req.url}`);
next();
});
Built-in Middleware
app.use(express.json()); // Parses JSON requests
app.use(express.urlencoded({ extended: true })); // Parses URL-encoded data
5. Handling Static Files
Express can serve static files like images, stylesheets, and JavaScript files.
app.use(express.static("public"));
Place files in a public
directory, and they can be accessed directly in the browser.
6. Working with URL Parameters and Query Strings
Express makes handling URL parameters and query strings simple.
Example:
app.get("/user/:id", (req, res) => {
res.send(`User ID: ${req.params.id}`);
});
Handling Query Strings
app.get("/search", (req, res) => {
res.send(`Search term: ${req.query.term}`);
});
Access this via http://localhost:3000/search?term=Node.js
.
7. Error Handling in Express
Express provides error-handling middleware to catch errors and respond properly.
Example:
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).send("Something went wrong!");
});
8. Setting Up a REST API with Express
Example:
const express = require("express");
const app = express();
const users = [
{ id: 1, name: "Alice" },
{ id: 2, name: "Bob" }
];
app.get("/users", (req, res) => {
res.json(users);
});
app.post("/users", (req, res) => {
const newUser = { id: users.length + 1, name: req.body.name };
users.push(newUser);
res.status(201).json(newUser);
});
app.listen(3000, () => console.log("API server running on port 3000"));
š Exercises
- 1. Create a basic Express server that responds with "Hello, Express!".
- 2. Modify the server to handle different HTTP methods for a
/users
route. - 3. Implement a middleware function that logs request details.
- 4. Create a route that serves static files from a directory.
5. Build a simple REST API with GET
, POST
, and DELETE
routes.
Conclusion
Express.js is a powerful framework that simplifies building web applications and APIs. This chapter covered how to create a server, handle routes, use middleware, and set up a REST API.