Express basics
Express is the most widely used web framework for Node.js. It's small and unopinionated: it gives you routing, request and response helpers, and middleware, and leaves the rest to you. Version 5 is the current major version.
npm install expressHello, Express
app.get(path, handler) registers a route: when a GET request for that path arrives, Express calls the handler. Compared to the raw http module, res.send sets the status, the Content-Type and the length for you.
On your computer, run it with
node --watch server.js. The--watchflag restarts the server whenever you save a file.
Route parameters and query strings
| Where the data is | Example URL | In Express |
|---|---|---|
| Route parameter | /products/3 with route /products/:id |
req.params.id → '3' |
| Query string | /products?sort=price |
req.query.sort → 'price' |
| Body (POST/PUT/PATCH) | JSON sent by the client | req.body (needs express.json()) |
| Headers | Authorization: Bearer … |
req.get('authorization') |
Parameters and query values are always strings. Convert them with Number(...) before comparing with numbers.
A JSON API with all four operations
Most APIs offer CRUD: Create, Read, Update, Delete. In Express that's one route per method:
The response object
| Method | Does |
|---|---|
res.send(body) |
Sends text, HTML or a Buffer, setting the Content-Type |
res.json(data) |
Sends data as JSON |
res.status(code) |
Sets the status code (chainable: res.status(404).json(…)) |
res.sendStatus(code) |
Sends just a status code, e.g. 204 |
res.set(name, value) |
Sets a header |
res.location(url) |
Sets the Location header |
res.redirect(url) |
Redirects (302 by default) |
res.cookie(name, value, options) |
Sets a cookie |
res.sendFile(path) |
Sends a file |
A handler must send exactly one response. Use return res.status(404)… so the function stops; sending a second response throws "Cannot set headers after they are sent to the client".
Serving a website too
express.static serves files from a folder: HTML, CSS, JavaScript, images. Combined with an API, one Express app can serve a whole website:
Practice
- Add
GET /todos/:idthat returns one todo or a 404. - Support
GET /todos?done=trueto list only finished todos (remember the value is the string'true'). - Return
400fromPOST /todoswhen the title is longer than 100 characters.
1.For the route /users/:id, where is the id of GET /users/7?
2.What does app.use(express.json()) do?
3.What's wrong with calling res.json(a) and then res.json(b) in one handler?