
If you're learning backend development with Node.js, then mastering Express.js is essential.
I created this simple Express.js cheat sheet that developers can quickly use while building APIs or preparing for interviews.
This guide covers the most important Express.js concepts in one place.
What is Express.js?
Express.js is a fast and minimal framework used to build:
- REST APIs
- Web applications
- Backend services
- Microservices
It simplifies server creation and routing in Node.js.
- Basic Express Server Setup const express = require('express'); const app = express();
app.listen(3000, () => {
console.log("Server running on port 3000");
});
This creates a simple server running on port 3000.
- Routing in Express.js
Routing defines how your server responds to requests.
app.get('/', (req, res) => {
res.send("Hello World");
});
app.post('/user', (req, res) => {
res.send("User created");
});
app.put('/user/:id', (req, res) => {
res.send("User updated");
});
app.delete('/user/:id', (req, res) => {
res.send("User deleted");
});
Common HTTP methods:
- GET
- POST
- PUT
- DELETE
- Middleware
Middleware functions run before sending a response.
app.use((req, res, next) => {
console.log("Request received");
next();
});
Examples of middleware:
- Authentication
- Logging
- Error handling
- Request Object
Useful properties:
req.params
req.query
req.body
req.headers
Example:
app.get('/user/:id', (req, res) => {
res.send(req.params.id);
});
- Response Methods
Common response functions:
res.send()
res.json()
res.status()
res.redirect()
Example:
res.status(200).json({ message: "Success" });
- Serving Static Files
app.use(express.static('public'));
This allows you to serve:
- Images
- CSS
- JavaScript files
- Important Commands
npm init -y
npm install express
node server.js
Quick Tip for Developers
In real projects:
- Use MVC structure
- Add error handling
- Use environment variables
- Secure your APIs
Top comments (0)