Routing: GET, POST, PUT, DELETE
9 min read
Routing: GET, POST, PUT, DELETE
A route is a combination of an HTTP method and a URL path. Express exposes methods on the app object that match every standard HTTP verb: app.get(), app.post(), app.put(), app.patch(), and app.delete().
js
app.get("/users", (req, res) => {
res.json({ message: "list all users" });
});
app.post("/users", (req, res) => {
res.status(201).json({ message: "create a user" });
});
app.put("/users/:id", (req, res) => {
res.json({ message: `replace user ${req.params.id}` });
});
app.delete("/users/:id", (req, res) => {
res.status(204).send();
});The path string is matched against the request URL. Express uses path-to-regexp under the hood, so you can use named segments (/:id), optional segments (/:id?), and wildcards (/*).
app.all()
app.all(path, handler) matches any HTTP method. It is useful for middleware that should run for a particular path regardless of verb, such as authentication guards.
Express matches routes in the order they are defined. Place more specific routes before generic catch-all routes to avoid shadowing.
Ready to test yourself?
Practice Express— quiz & coding exercises