Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to use express router
In earlier examples, we wrote all routing code in a single file App.js. But in real world scenarios, we have to split the code into multiple files.
We can create separate files and import them but express gives a router mechanism which is easy to use.
Create a separate file called route.js (name can be anything)
Create router using express −
const express = require('express');
const router = express.Router();
exporting router −
module.exports = router;
Adding routing functions −
router.get('/add-username', (req, res,next)=>{
res.send('<form action="/post-username" method="POST"> <input type="text" name="username"> <button type="submit"> Send </button> </form>');
});
router.post('/post-username', (req, res, next)=>{
console.log('data: ', req.body.username);
res.redirect('/');
});
Similar to functions we used in App.js for creating paths , we used router .
Import the router in App.js file −
const route = require('./routes');
add a middleware for using router in App.js file.
app.use(route);
with these changes the complete App.js file is −
const http = require('http');
const express = require('express');
const bodyParser = require('body-parser');
const route = require('./routes');
const app = express();
app.use(bodyParser.urlencoded({extended: false}));
app.use(route); app.use('/', (req, res,next)=>{
res.send('<h1> first midleware: Hello Tutorials Point </h1>');
});
const server = http.createServer(app);
server.listen(3000);
route.js
const express = require('express');
const router = express.Router();
router.get('/add-username', (req, res,next)=>{
res.send('<form action="/post-username" method="POST"> <input type="text" name="username"> <button type="submit"> Send </button> </form>');
});
router.post('/post-username', (req, res, next)=>{
console.log('data: ', req.body.username);
res.redirect('/');
});
module.exports = router;
The router middleware should be placed before any url handling if present in App.js. Because code execution works from top to bottom in App.js file.
If any additional routers required , we can create separate files similar to routes.js and import it in App.js with another middleware in order for using that router.