‘express.Router’ function is used to create a router
object.
A router is capable to perform middleware and route
functions. You can pass the router to an
argument to app.use() method (or) router.use method.
Let’s see it by an example.
Let’s build an application like above.
mainApp contains an index.js file, it is the starting
point of the application.
mainApp/welcomeMessages/index.js contains all the routes
that handles welcome messages.
mainApp/timeMessages/index.js contains all the routes
that handle time related messages.
Developing the
application.
Create below folders.
a.
mainApp
b.
mainApp/welcomeMessages
c.
mainApp/timeMessages
mainApp/timeMessages/index.js
const express = require('express') const router = express.Router() module.exports = () => { router.get("/today", (req, res) => { return res.send(new Date().toString()) }) return router }
mainApp/welcomeMessages/index.js
const express = require('express') const router = express.Router() module.exports = () => { router.get("/hello", (req, res) => { return res.send("Hello, How are you") }) router.get("/welcome", (req, res) => { return res.send("Welcome to node.js programming") }) return router }
mainApp/index.js
const express = require('express') const timeRoutes = require('./timeMessages') const welcomeRoutes = require('./welcomeMessages') //Put new Express application inside app variable const app = express() const port = 8080 app.use('/time', timeRoutes()) app.use('/greetMe', welcomeRoutes()) app.get('/', (req, res) => res.send('Welcome to home page')) // Start the express application on port 8080 and print server start message to console. app.listen(port, () => console.log(`Application started listening on port ${port}!`));
As you see the snippet, I defined all my welcome message
routes in below file.
mainApp/welcomeMessages/index.js
I defined all my time related routes in below file.
mainApp/timeMessages/index.js
Below statement redirects all the /time/* urls to
timeRoutes
app.use('/time', timeRoutes())
Below statement route all the /greetMe/* urls to
welcomeRoutes.
app.use('/greetMe', welcomeRoutes())
Go to the parent directory of mainApp and execute ‘node
mainApp’.
Open browser and hit the url ‘http://localhost:8080/’.
Open browser and hit the url ‘http://localhost:8080/time/today’.
Hit the url ‘http://localhost:8080/greetMe/hello’ in
browser.
Hit the url ‘http://localhost:8080/greetMe/welcome’ in
the browser.
No comments:
Post a Comment