Node.js Lesson 7: Express.js Basics
Express.js is the most popular Node.js framework. It makes building web servers and APIs much faster and cleaner than the raw http module.
Setup
npm install express
# Install nodemon for auto-restart:
npm install -D nodemon
# Add to package.json scripts:
"dev": "nodemon app.js"
Your First Express App
const express = require("express");
const app = express();
// Parse JSON request bodies
app.use(express.json());
// Routes
app.get("/", (req, res) => {
res.send("<h1>Hello from Express!</h1>");
});
app.get("/api/hello", (req, res) => {
res.json({ message: "Hello!", timestamp: new Date() });
});
app.get("/api/users/:id", (req, res) => {
const { id } = req.params;
res.json({ userId: id, name: "User " + id });
});
// Start server
app.listen(3000, () => {
console.log("Server running on http://localhost:3000");
});
Request Object
app.get("/search", (req, res) => {
// Query strings: /search?q=node&limit=10
const { q, limit = 10 } = req.query;
res.json({ query: q, limit: Number(limit) });
});
app.post("/users", (req, res) => {
// JSON body from POST request
const { name, email } = req.body;
res.status(201).json({ id: Date.now(), name, email });
});
🏋️ Practice Task
Build an Express app with these routes: GET / (HTML welcome page), GET /api/products (return an array of 3 product objects), GET /api/products/:id (return one product by id), POST /api/products (accept JSON body, return the created product with an id). Test with a tool like Postman or Thunder Client.
💡 Hint: Create an array const products = […]. For GET /:id: find by id with products.find(p => p.id === Number(req.params.id)).