Map URL Patterns to Handler Functions
Routing Basics
Routing matches HTTP method + URL path to a handler function. The bedrock of every Express app.
What you'll learn
- Define routes per HTTP method
- Send responses
- Recognize the request/response objects
A route matches an incoming request to a handler. The match is based on HTTP method + URL path.
Anatomy of a Route
app.get("/users", (req, res) => {
res.json([{ id: 1, name: "Ada" }]);
}); Parts:
app.get— match GET requests"/users"— match the path/users(req, res) => { ... }— handler function
All HTTP Methods
app.get("/posts", listPosts);
app.post("/posts", createPost);
app.get("/posts/:id", getPost);
app.patch("/posts/:id", updatePost);
app.delete("/posts/:id", deletePost); Every standard HTTP method has a matching app.METHOD. Less common
ones too: app.head, app.options, app.copy, app.purge.
The Request Object
req carries everything about the incoming request:
app.get("/users", (req, res) => {
console.log(req.method); // 'GET'
console.log(req.path); // '/users'
console.log(req.url); // '/users?expand=true'
console.log(req.headers); // { 'user-agent': ..., 'accept': ... }
console.log(req.query); // { expand: 'true' }
console.log(req.params); // {} (covered next)
console.log(req.body); // {} (needs middleware — covered later)
console.log(req.ip); // client IP
}); The Response Object
res is your toolkit for replying:
res.send("Hello!"); // plain text or HTML
res.json({ ok: true }); // JSON
res.status(201).json({ id: 42 }); // status + JSON
res.status(404).end(); // empty response
res.redirect("/login"); // 302 redirect
res.redirect(301, "/new-location"); // permanent redirect
res.set("X-Total", "100"); // set a header A Complete Example
import express from "express";
const app = express();
app.use(express.json());
const users = [
{ id: 1, name: "Ada" },
{ id: 2, name: "Linus" },
];
app.get("/users", (req, res) => {
res.json(users);
});
app.post("/users", (req, res) => {
const user = { id: users.length + 1, ...req.body };
users.push(user);
res.status(201).json(user);
});
app.listen(3000); Test with curl:
curl http://localhost:3000/users
# [{"id":1,"name":"Ada"},{"id":2,"name":"Linus"}]
curl -X POST http://localhost:3000/users \
-H "content-type: application/json" \
-d '{"name":"Grace"}'
# {"id":3,"name":"Grace"} Up Next
Path parameters — /users/:id.