Ah, Express.js! The superhero framework for Node.js that makes building web applications feel like assembling LEGO blocks—simple, modular, and oddly satisfying. If you’re wondering how to use Express.js for routing, grab a cup of coffee, and let’s embark on this hilarious yet educational journey into the world of Node.js routing!
What is Routing in Express.js?
Routing is the process of determining how an application responds to a client request to a particular endpoint (URL + HTTP method). Think of it as giving clear directions to your application:
- "If someone asks for
/home
, show them the homepage." - "If someone posts to
/login
, check their credentials."
Express.js makes this process super easy and intuitive, which is why it’s the go-to framework for Node.js developers worldwide.
Prerequisites
Before we dive in, make sure you have:
- Node.js installed
- Express.js installed (
npm install express
) - A basic understanding of JavaScript
- A willingness to laugh at bad jokes
Step 1: Setting Up an Express App
First, create a new project and install Express.js:
mkdir express-routing && cd express-routing
npm init -y
npm install express
Create a new file called server.js
and add the following boilerplate code:
const express = require('express');
const app = express();
const port = 3000;
app.listen(port, () => {
console.log(`Server is running on http://localhost:${port}`);
});
Run the server with:
node server.js
Your server is now alive.
Step 2: Creating Basic Routes
Express routes are defined using HTTP methods like GET
, POST
, PUT
, and DELETE
. Let’s add some routes:
app.get('/', (req, res) => {
res.send('Welcome to my Express.js app!');
});
app.get('/about', (req, res) => {
res.send('This is the about page. Here we brag about our greatness.');
});
app.get('/contact', (req, res) => {
res.send('Contact us at: imaginary@company.com');
});
Now visit http://localhost:3000/
in your browser.
Step 3: Handling Route Parameters
Sometimes, you need dynamic routes, like fetching a user by ID. Express makes this easy:
app.get('/users/:id', (req, res) => {
const userId = req.params.id;
res.send(`You requested user with ID: ${userId}`);
});
Try visiting http://localhost:3000/users/42
.
Step 4: Using Middleware for Routing
Middleware functions in Express.js are like bouncers at a club. They process requests before they reach their final destination. Let’s create a simple middleware:
const logger = (req, res, next) => {
console.log(`Request received at ${req.url}`);
next();
};
app.use(logger);
Now, every request will be logged before being processed.
Step 5: Organizing Routes with Express Router
As your app grows, you don’t want all routes in server.js
. Instead, let’s use Express Router to modularize them.
Create a new file called routes.js
:
const express = require('express');
const router = express.Router();
router.get('/', (req, res) => res.send('Home Page'));
router.get('/about', (req, res) => res.send('About Page'));
router.get('/contact', (req, res) => res.send('Contact Page'));
module.exports = router;
Then, modify server.js
to use this router:
const express = require('express');
const app = express();
const port = 3000;
const routes = require('./routes');
app.use('/', routes);
app.listen(port, () => {
console.log(`Server running on http://localhost:${port}`);
});
Your routes are now neatly organized.
Conclusion
Congratulations. You now know how to:
- Create basic routes in Express.js
- Handle dynamic route parameters
- Use middleware for logging
- Organize routes with Express Router
Now go forth and build your dream API or web app, and remember—Express.js routing is your best friend in making that happen.
0 Comments