ES5 vs ES6: Syntax Comparison Table
CommonJS is the default in Node.js. ES Modules need
"type": "module" in package.json. You cannot mix them in the same file.Install Express
Express Server: ES5 (CommonJS)
Express Server: ES6 (ES Modules)
First add topackage.json:
Side-by-Side Comparison
Core Express Concepts
The Request-Response Cycle
1
Client sends request
Browser or mobile app sends HTTP request to a URL with a method (GET, POST…).
2
Express matches route
Express checks registered routes for a matching path and method.
3
Middleware runs
Each registered
app.use() function runs in order before the route handler.4
Route handler executes
The matched handler runs business logic and queries the database.
5
Response sent
Handler calls
res.json(), res.send(), or res.status().json() to respond.Essential Express Methods
req and res Objects
ES6 Features Used Daily in Node.js
Arrow Functions
Template Literals
Destructuring
Spread Operator
async/await
async/await is syntactic sugar over Promises. An async function always returns a Promise. await pauses execution until the Promise resolves. Always wrap await in try/catch.Error Handling in Express
Centralized Error Handler (must be LAST)
Passing Errors from Async Routes
Key Terms
Common Mistakes
Mixing require() and import
Mixing require() and import
Once you add
"type": "module", all .js files must use import. If one file uses require(), rename it to .cjs.Forgetting express.json()
Forgetting express.json()
Without
app.use(express.json()), req.body is undefined for POST and PUT requests. This is the most common beginner error.Not returning after res.send()
Not returning after res.send()
Always
return res.status(404).json(...) to exit the function. Without return, Express tries to send two responses and crashes with “headers already sent.”Error handler with wrong number of params
Error handler with wrong number of params
Error handling middleware must have exactly 4 parameters:
(err, req, res, next). With 3 params, Express treats it as a normal middleware and errors bypass it.