Install Express and structure your first server with routes, URL parameters, and middleware.
Open this lesson in KodokonYou already know how to start a server with the native http module: everything is manual there, from reading the URL to assembling the headers. Express is the framework that standardized web development on the Node side: routing, middleware, a concise API, without hiding anything about the protocol. Create a project and install it.
mkdir kodokon-api
cd kodokon-api
npm init -y
npm install expressAdd the type property with the value module to your package.json: the whole project will use ES modules. Then create server.js. A few lines are enough for a working server: you create the application, declare a route, and listen on a port.
import express from "express";
const app = express();
app.get("/", (req, res) => {
res.send("Kodokon API online");
});
app.listen(3000, () => {
console.log("http://localhost:3000");
});A route maps an HTTP method and a path to a function. Dynamic segments are declared with a colon: in /users/:id, the value is available in req.params.id. Query parameters (?q=node) show up in req.query. Keep the distinction in mind: the path identifies the resource, the query string refines the request.
app.get("/users/:id", (req, res) => {
const { id } = req.params;
res.json({ id, name: "User " + id });
});
app.get("/search", (req, res) => {
const { q } = req.query;
res.json({ query: q ?? "" });
});A middleware is a function that runs between the arrival of the request and your route. Its signature: (req, res, next). It can enrich req, respond directly, or hand off with next(). Express is fundamentally just a chain of middleware: logging, authentication, body parsing. This one logs every request with its duration:
app.use((req, res, next) => {
const start = Date.now();
res.on("finish", () => {
const ms = Date.now() - start;
console.log(`${req.method} ${req.url} ${ms}ms`);
});
next();
});/users/:id. Where do you read the value of id?req.query.idreq.params.idreq.body.idnext() do?package.json to use the import syntax in Node.js?type property set to moduleesm property set to true