Hey there! If you're diving into the world of Node.js and building web applications, chances are you’ve come across Express.js. It’s one of the most popular frameworks for Node and honestly, it makes backend development so much easier.
I know it can feel overwhelming at first, especially when you're trying to remember all the routes, middleware, and other stuff. So I put together this Express.js cheatsheet just for you, to keep things simple and easy to follow.
Let’s jump right in!
🚀 Setting Up Express
Before anything else, you’ll need to install Express in your Node.js project.
npm install express
Then in your main file (like app.js
or server.js
), set it up like this:
const express = require('express');
const app = express();
const port = 3000;
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});
🛣️ Creating Routes
Routes are how your app responds to client requests. Here’s how to create some basic ones:
app.get('/', (req, res) => {
res.send('Hello, world!');
});
app.post('/submit', (req, res) => {
res.send('Form submitted');
});
app.put('/update/:id', (req, res) => {
res.send(`Updated item with ID ${req.params.id}`);
});
app.delete('/delete/:id', (req, res) => {
res.send(`Deleted item with ID ${req.params.id}`);
});
🧱 Using Middleware
Middleware functions are like the gatekeepers, they run before your route handlers. You can use them to handle stuff like logging, authentication, or parsing data.
Here’s how you use a simple middleware:
app.use(express.json()); // Parses JSON body
app.use(express.urlencoded({ extended: true })); // Parses form data
Custom middleware example:
app.use((req, res, next) => {
console.log(`${req.method} ${req.url}`);
next(); // Don’t forget this, or it won’t move on
});
📦 Serving Static Files
Want to serve images, CSS, or JS files? Just do this:
app.use(express.static('public'));
Now if you have a file like public/style.css
, it will be available at http://localhost:3000/style.css
.
📥 Handling Query Params and Body
Getting query params from URL:
app.get('/search', (req, res) => {
const searchTerm = req.query.q;
res.send(`You searched for: ${searchTerm}`);
});
Getting data from POST body:
app.post('/contact', (req, res) => {
const { name, email } = req.body;
res.send(`Thanks, ${name}! We’ll contact you at ${email}`);
});
🧭 Route Parameters
You can use :paramName
to define dynamic values in URLs.
app.get('/user/:username', (req, res) => {
const username = req.params.username;
res.send(`Hello, ${username}`);
});
💥 Handling 404 Errors
If no route matches, you can catch it like this:
app.use((req, res) => {
res.status(404).send('Sorry, page not found');
});
🛠️ Organizing Routes in Separate Files
As your app grows, it’s a good idea to move routes into separate files.
// routes/userRoutes.js
const express = require('express');
const router = express.Router();
router.get('/profile', (req, res) => {
res.send('User profile page');
});
module.exports = router;
// In your main app file
const userRoutes = require('./routes/userRoutes');
app.use('/user', userRoutes);
💡 Final Tips
- Always handle errors properly in your routes.
- Use tools like Postman to test your APIs.
- Don't forget to restart your server if you’re not using something like
nodemon
.
Wrapping Up
That’s pretty much the core of what you’ll use daily with Express.js. Of course, there’s a lot more you can do like templating, sessions, authentication, etc., but this cheatsheet should cover most of the basic stuff you need to get started or build a simple app.
Keep this page bookmarked or save it somewhere so you can quickly glance at it when your brain decides to go blank (happens to the best of us).
Happy coding, and may your APIs always respond on time!
Comments
Please login to publish your comment!
By logging in, you agree to our Terms of Service and Privacy Policy.
No comments here!