Home / Node.js / Lesson 4

Express: routes and middleware

Intermediate 9 min read Lesson 4 of 6

Express is a small HTTP framework. It is not part of Node itself; you add it with npm.

npm install express
import express from 'express';

const app = express();
app.use(express.json()); // parse JSON bodies

app.get('/', (req, res) => {
  res.json({ ok: true, message: 'API is up' });
});

app.listen(3000, () => console.log('http://localhost:3000'));

app.get, app.post, app.put, app.delete match HTTP methods. res.json sets Content-Type and stringifies. req.params comes from /users/:id. req.query is the query string. req.body is filled only if express.json() (or urlencoded) ran first.

Middleware is a function (req, res, next). Call next() to continue, or send a response and stop. Order matters: json parser before routes that read req.body.