node js routes in separate file using express
In this article, we will show how to manage your routes in a separate file from app.js using express. generally, we manage in a single file for simple application(single-page). but when we need to multi-page, and hybrid web application at that time we will manage routes and create separate files.
Express router is a class library, it helps too create router and handle the HTTP request (such as GET, POST, PUT, DELETE, etc.). lets us see simple example for node js routes in a separate file using express.
First we will install nodejs and create simple app. for it you can follow below example Url.
Hello world application using nodejs and express
Now, we will create home.js, contact.js and about.js in view directory. in that file in we create the route and pass the simple message for test purpose. so you can see below code.
app.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | const express = require('express'); var home = require('./view/home'); var about = require('./view/about'); var contactus = require('./view/contact'); var app = express(); app.use(express.json()); app.use(express.urlencoded({ extended: false })); app.use('/', home); app.use('/about', about); app.use('/contact', contactus); app.listen(3000, function(){ console.log("Express server listening on port ",3000); }); module.exports = app; |
view/home.js
1 2 3 4 5 6 | var express = require('express'); var router = express.Router(); router.get('/', function(req, res, next) { res.end('Welcome to You in Home Page'); }); module.exports = router; |
view/about.js
1 2 3 4 5 6 | var express = require('express'); var router = express.Router(); router.get('/', function(req, res, next) { res.end('Welcome to You in About Page'); }); module.exports = router; |
view/contact.js
1 2 3 4 5 6 | var express = require('express'); var router = express.Router(); router.get('/', function(req, res, next) { res.end('Welcome to You in Contact Page'); }); module.exports = router; |
Finally, when you will run the application then it will show the home page on the root route and if you pass a particular page in browser Url (such as about and contact) then it will display a particular page.