Node.jsintermediate 9 min
Routing, route parameters and query strings in a few lines with the Express framework.
How to install Express, define routes for different URLs, read route parameters and query strings, and send text or JSON back.
The built-in http module makes you check URLs and methods by hand. Express is the most popular Node web framework: it turns that into short, readable route definitions, and is the base that many other tools build on.
Install it in your project:
An Express app is made of routes. Each route says: for this method and this path, run this function.
app.get, app.post, app.put, app.delete match HTTP methods.req.params holds route parameters from the path: /users/:id gives req.params.id.req.query holds the query string: /search?q=node gives req.query.q.res.send("text") sends text or HTML, res.json(object) sends JSON, and res.status(404) sets the status code.app.listen(port, callback) starts the server.Save as app.mjs (this is a real server that keeps running until you press Ctrl+C):
express() creates the app./ route answers with plain text./hello/:name captures whatever is in the :name position. Visiting /hello/Asha sends Hello, Asha!./search reads ?q=... from the URL and replies with JSON. Visiting /search?q=node gives {"query":"node"}, and /search alone gives {"query":null}.listen starts the server and prints a message.The script below starts the server, calls its own routes with fetch, prints the replies and shuts down, so you can see everything in one run. Save it as try.mjs, run npm install express, then node try.mjs.
npm install express, which gives "Cannot find package".res.send, res.json or res.end.req.params for path values, req.query for query strings.res.send and res.json reply; app.listen starts the server.Next: building a REST API.
npm init -y
npm install expressapp.get("/path", (req, res) => { ... });import express from "express";
const app = express();
app.get("/", (req, res) => {
res.send("Hello from Express");
});
app.get("/hello/:name", (req, res) => {
res.send(`Hello, ${req.params.name}!`);
});
app.get("/search", (req, res) => {
res.json({ query: req.query.q ?? null });
});
app.listen(3000, () => {
console.log("Listening on http://localhost:3000");
});