Express.js web app [Part 3] | working with routers š»
Welcome to part 3 of our series on building a web app with Express.js! In
this article, we will be exploring the concept of routers in Express.js and
how they can be used to organize and modularize your web application.
What are Routers in Express.js?
Routers in Express.js are a way to create modular, mountable route handlers.
They provide a way to break up your application into smaller, more manageable
pieces, making it easier to organize your code and maintain your web app.
Each router instance is essentially a mini-app, capable of performing its own
routing and middleware functions.
Working with Routers
Let’s create a basic router in our Express.js web app. First, we need to
require the express module and create an instance of the router:
const express = require('express');
const router = express.Router();
Now, we can define routes on this router instance, just as we would on the
main app object:
router.get('/', function(req, res) {
res.send('This is the homepage');
});
router.get('/about', function(req, res) {
res.send('This is the about page');
});
Finally, we need to mount the router on our main app object using the
app.use()
method:
const app = express();
app.use('/', router);
app.listen(3000, function() {
console.log('Server is running on port 3000');
});
Now, when a request is made to our web app, Express will use the router to
match the request’s URL to one of the defined routes and execute the
corresponding handler function.
Conclusion
Routers in Express.js are a powerful tool for organizing and modularizing
your web app. They allow you to break up your application into smaller,
more manageable pieces, making it easier to maintain and update your code.
In the next article, we will explore more advanced features of Express.js
and how they can be used to build a fully-featured web app.
for those who didn't see the commands because of the watermark:
npm i nodemon –save-dev
npm run dev