Node.js lets JavaScript run outside the browser, so students can build servers, APIs, command-line tools, and full-stack applications. Express is a small web framework for Node.js that makes routing, middleware, and HTTP responses easier to organize. This cheat sheet gives students a quick reference for the commands, patterns, and code structure used in beginner server projects.
It is useful when starting a new app, debugging routes, or reviewing how requests move through a server.
Key Facts
- Run a JavaScript file with Node using the command node filename.js.
- Start a new Node project with npm init -y, which creates a package.json file with default settings.
- Install Express with npm install express, then import it with const express = require('express').
- Create an Express app with const app = express(), then start the server with app.listen(PORT, callback).
- A basic GET route uses app.get('/path', (req, res) => { res.send('message'); }).
- Use app.use(express.json()) so Express can read JSON data sent in the request body.
- Common CRUD methods are GET for read, POST for create, PUT or PATCH for update, and DELETE for remove.
- Common HTTP status codes include 200 OK, 201 Created, 400 Bad Request, 404 Not Found, and 500 Server Error.
Vocabulary
- Node.js
- Node.js is a runtime that allows JavaScript code to run on a server or computer outside a web browser.
- npm
- npm is the Node package manager used to install libraries, run scripts, and manage project dependencies.
- Express
- Express is a lightweight Node.js framework that helps create web servers, APIs, routes, and middleware.
- Route
- A route is a rule that connects an HTTP method and URL path to a function that handles the request.
- Middleware
- Middleware is a function that runs between the incoming request and the final route response.
- CRUD
- CRUD stands for create, read, update, and delete, which are the four basic operations used to manage data.
Common Mistakes to Avoid
- Forgetting app.use(express.json()) is wrong because req.body will be undefined when the client sends JSON data.
- Putting a catch-all route before specific routes is wrong because Express checks routes in order and may stop before reaching the intended handler.
- Using the wrong HTTP method is wrong because app.get('/users') and app.post('/users') are different routes with different purposes.
- Sending more than one response in the same route is wrong because each request should receive only one final response, such as res.send() or res.json().
- Hard-coding a port without a fallback is risky because hosted apps often require process.env.PORT, so use const PORT = process.env.PORT || 3000.
Practice Questions
- 1 Write the terminal commands to create a new Node project and install Express.
- 2 Given const PORT = 3000, write a short app.listen statement that starts the server and logs Server running.
- 3 Write an Express route for GET /health that sends the JSON response {"status":"ok"}.
- 4 Explain why middleware order matters in an Express app, especially when using express.json(), route handlers, and error handlers.
Understanding Node.js & Express Quick Reference
Node.js uses an event driven model. A server spends much of its time waiting for network requests, file reads, or database results. Instead of stopping while it waits, Node.js can begin other work.
When a waiting task finishes, its callback or promise handler can run. This makes Node.js useful for applications that handle many small requests. Students should understand that JavaScript still runs one main piece of code at a time.
A long calculation can block that main thread and make every user wait. For slow operations, use asynchronous code carefully and avoid large loops inside a request handler.
A web request contains more than its path. It has a method, headers, optional data, and sometimes values in the URL. Route parameters identify one specific item, such as a student ID in a path.
Query values filter or sort a collection, such as showing assignments for one subject. Request bodies carry data for actions like creating an account or changing a record. A good server checks all incoming values before using them.
It should confirm that required fields exist, that numbers are really numbers, and that text follows expected limits. Input from a browser is never automatically trustworthy.
Middleware works like a series of checkpoints between a request and its final route. One middleware function may record the request. Another may check whether the user is signed in.
Another may parse data or validate it. Each function must either send a response or pass control onward. If it does neither, the request can appear to freeze.
The order matters because Express uses middleware in the order it is registered. Put general tools near the beginning, then route specific checks, then routes. Error handling middleware belongs near the end so it can catch problems passed from earlier code.
CRUD labels describe a common pattern, but a real API needs clear rules. Creating an item should return the new item or enough information to find it. Updating should define whether every field is required or only changed fields are accepted.
Deleting may remove data permanently, or it may mark it as inactive for later recovery. Status codes tell the client what happened, yet the response body should give useful details too. A bad request should explain which field failed without exposing private system details.
A missing route differs from a route that exists but cannot find a requested record. Server errors should be logged for developers while users receive a simple safe message.
Most beginner bugs come from small mismatches. The client may call the wrong path, use the wrong method, forget a header, or send invalid JSON. Check the browser network panel, server terminal output, and the exact request data.
Use environment variables for secrets and port settings rather than placing passwords in source files. Keep package versions recorded so classmates can install the same dependencies.
Build one route at a time and test normal input, missing input, unusual input, and requests for records that do not exist. This habit makes server code easier to understand and safer to extend.