Express flashcards
The small, popular web framework for Node.js.
Beginner friendly, starts from zero
0
Express at a glance
Express is a small JavaScript toolkit for building web servers that answer requests from browsers and apps.
A server is a restaurant kitchen: requests are orders coming in, responses are dishes going out, and Express is the head waiter who sends each order to the right cook.
Words you will meet
- Request
- A question an app or browser sends to a server
- Response
- The answer the server sends back
- Route
- A method plus a path plus the function that answers it
- Middleware
- A function every request passes through before its handler
- JSON
- Plain text for sending data, like {"name": "Ravi"}
- Status code
- A three-digit number that says how a request went, like 404
- Header
- A short label on the outside of a request or response
- Port
- A numbered door on a computer where the server listens
The steps
- 1. Start from zero (12 cards): What a server is, how requests and responses work, and the words Express uses.
- 2. Core basics (14 cards): Your first Express 5 API: routes, params, JSON in and out, status codes and static files.
- 3. Next steps (16 cards): Middleware, routers, Express 5 errors and paths, validation, CORS and file uploads.
- 4. Go deeper (16 cards): Security headers, proxies, cookies, testing, performance, observability and production shutdown.
All 12 cards in Start from zero
- What is Express, in one plain sentence?
- Express is a small toolkit for building a web server: a program that waits for questions from browsers and apps and sends back answers, written in JavaScript.
- What are a request and a response, and where do you meet them every day?
- A request is a question an app sends, like "show my orders". The response is the answer the server sends back. Every time an app loads your messages or bills, this happens in a second.
- What problem does Express solve? What was it like without it?
- Plain Node.js can answer requests, but you write long if-checks for every address and read form data byte by byte. Express gives ready parts for this, so a server takes a few lines.
- What are Node.js, npm and a package?
- Node.js runs JavaScript outside the browser, on a computer or server. A package is ready-made code you can add to your project, and npm is the tool that downloads packages, like Express.
- Name the parts of this web address.
localhostmeans your own computer,3000is the port (a numbered door on it),/ordersis the path, and?page=2is the query string, extra details for the request.- What are methods like GET and POST, and what is a route?
- A method is the verb of a request: GET reads, POST creates, PUT or PATCH changes, DELETE removes. A route is a method plus a path plus the function that answers it, called a handler.
- What are JSON, a body and a header?
- JSON is plain text for data, like
{"name": "Ravi"}. The body is the data carried inside a request or response. Headers are short labels on the outside, like the type of content or a key. - What is a status code?
- A three-digit number at the start of every response that says how it went: 200 OK, 201 created, 404 not found, 500 the server broke. Apps read it before the body.
- What do middleware and async mean?
- Middleware is a function every request passes through before its handler, like a security check before the gate. Async code waits for slow work, such as a database, without freezing the server.
- What do you need before you start?
- Node.js 18 or newer, a text editor, and a terminal: the window where you type commands. Then
npm install expressadds Express to your project folder. - First tiny win: what does each line of this server do?
- Line 2 creates the app, line 3 adds a route that sends a reply for the home path, and
listenstarts waiting on port 3000. Openlocalhost:3000in a browser to see it. - What will you be able to do after this topic?
- Build a small API that reads requests, sends JSON with the right status codes, checks input with middleware, handles errors in one place, and is ready to run safely in production.
Express cheatsheet
App setup
const app = express()Create the appapp.use(express.json({ limit: "100kb" }))Parse JSON bodiesapp.use(express.urlencoded())Parse HTML form postsapp.use("/api", router)Mount a router on a prefixapp.set("trust proxy", 1)Trust one proxy hopapp.disable("x-powered-by")Hide the framework headerapp.listen(port, (err) => {})Start, error in callback (v5)
Request
req.params.idPath segment (string)req.query.pageQuery value (read-only in v5)req.bodyParsed body,undefinedwithout parserreq.get("authorization")Header, any casereq.ipClient IP (needstrust proxy)req.originalUrlFull URL incl. mount prefixreq.is("application/json")Check content type
Response
res.status(201).json(obj)Status and JSONres.sendStatus(204)Status onlyres.redirect(301, url)Permanent redirectres.set("Cache-Control", "no-store")Set a headerres.cookie(name, val, opts)Set a cookieres.download(path, name)File as attachmentres.sendFile(name, { root })File inline from a folderres.locals.userPer-request shared data
Express 5 paths
/users/:idNamed parameter/files/*filepathNamed wildcard, array value/files{/*filepath}Wildcard that also matches/files/posts{/:page}Optional segment (was:page?)/invoices/:id.pdfParam followed by literal text/price\(usd\)Escape reserved characters
Middleware shapes
(req, res, next) => next()Normal middleware(err, req, res, next) => {}Error handler, after routesnext(err)Jump to the error handlernext("route")Skip to the next matching routeapp.get(path, auth, validate, handler)Per-route chainrouter.route(path).get().put()Many verbs, one path