What is Routing in node.js?
Routing defines the way in which the client requests are handled by the application.
Express.js has an "app" object corresponding to HTTP. We define the routes by using the methods of this "app" object.
This app object specifies a callback function, which is called when a request is received.
There are two ways to implement routing in node.js
By Using Framework :- Express.Js
Without using Framework
By Using Framework :-
GET method request :- app.get()
File Name :
var express = require('express');
var app = express();
app.get('/', function(req, res) {
res.send('Hello Sana')
})
POST method request :- app.post()
File Name :
var express = require('express')
var app = express()
app.post('/', function(req, res) {
res.send('Hello Sana')
})
For handling all HTTP methods (i.e. GET, POST, PUT, DELETE etc.) use app.all() method:
File Name :
var express = require('express')
var app = express()
app.all('/', function(req, res) {
console.log('Hello Sana')
next() // Pass the control to the next handler
})
The next() method is used to hand off the control to the next callback. Sometimes we use app.use() to specify the middleware function as the callback.
Example
File Name : App.js
var express = require('express');
var path = require('path');
var bodyParser = require('body-parser');
var mysql = require('mysql');
var conn = require('./database/db');
var app = express();
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static(path.join(__dirname, 'public')));
app.use(session({
secret: 'mahi*786',
// resave: true,
resave: false,
saveUninitialized: true,
// cookie: { maxAge: 60000 }
cookie: { maxAge: 30 * 24 * 60 * 60 * 1000 }
}))
// #################### Routes Setup Start #######################
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var empRouter = require('./routes/emp');
app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/emp', empRouter);
// #################### Routes Setup End #######################
app.listen(3000, function () {
console.log('Node app is running on port 3000');
});
module.exports = app;
Routes :-
File Name : routes/emp.js
var express = require('express');
var router = express.Router();
var conn = require('../database/db');
var path = require('path');
router.get('/employee_show',function(req, res){
res.render('emp-show', {title: 'Login'})
});
router.post('/employee_action',function(req, res, next){
var email = req.body.email;
var password = req.body.password;
});
module.exports = router;
Routing without Framework:
File Name :
var http = require('http');
// Create a server object
http.createServer(function (req, res) {
// http header
res.writeHead(200, {'Content-Type': 'text/html'});
var url = req.url;
if(url ==='/about') {
res.write(' Welcome to about us page');
res.end();
}
else if(url ==='/contact') {
res.write(' Welcome to contact us page');
res.end();
}
else {
res.write('Hello World!');
res.end();
}
}).listen(3000, function() {
// The server object listens on port 3000
console.log("server start at port 3000");
});
Route Definition :-
File Name :
app.method(PATH, HANDLER)
app is an instance of express.
method is an HTTP request method (lowercase).
PATH is a path on the server.
HANDLER is the function executed when the route is matched.
There are two ways of using the router methods.
File Name :
// Method 1
router.route('/users')
.get(function (req, res, next) { ... })
.post(function (req, res, next) { ... });
// Method 2
router.get('/users', function (req, res) { ... });
router.post('/users', function (req, res) { ... });
Note :-
File Name :
We can use the same (‘/users’) route for multiple methods like GET, POST within a Node application.
Route paths :-
The route paths in combination with a request method define the endpoints at which requests can be made. It can be strings, string patterns, or regular expressions.
The characters ?, +, *, and () are subsets of their regular expression counterparts.
File Name :
app.get('/', function (req, res) {
res.send('root')
})
File Name :
And this route path will match requests to /home.
app.get('/home', function (req, res) {
res.send('home')
})
File Name :
While this route path will match requests to /profile.text.
app.get('/profile.text', function (req, res) {
res.send('profile.text')
})
File Name :
Examples of route paths based on string patterns:
This route path will match ab and cd.
app.get('/ab?cd', function (req, res) {
res.send('ab?cd')
})
Route parameters
These are named URL segments that are used to capture the values specified at their position in the URL. The captured values are populated through the req.params object, with the respective key name defined in the path of request method.
File Name :
app.get(‘/users/:userId/orders/:orderId’, function (req, res) {
res.send(req.params)
})
Route handlers :-
It can be in the form of a function, an array of functions, or even combinations of both.
We can provide multiple callback functions that behave like middleware to handle a request. But, the only exception is that these callbacks might invoke next(‘route’) to bypass the remaining route callbacks.
File Name :
app.get('/getDetails', function (req, res, next) {
console.log('invoke response using next callback function ...')
next()
}, function (req, res) {
res.send('Here are the details!....')
})
Express Router
Express JS use express.Router class to create modular and mountable route handlers. The Router instance also known as Mini-app, is a complete middleware routing system in ExpressJS.
File Name :
const express=require("express");
const router=express.Router();
Router.get
Now we are using Router.use to add a middleware function.
File Name :
// Create admin route
/* admin.js */
const express=require("express");
const router=express.Router();
router.get('/',(req,res)=>{
console.log("hi admin");
res.status(200).send("hi admin");
});
module.exports=router;
Run route in main app
File Name : aap.js
/* app.js */
const express=require('express');
const app=express();
const admin=require('./admin');
app.use('/admin',admin);
app.listen(3000)
Router Example
we are using two different modules , admin and user.
Admin route
File Name :
/* admin.js */
const express=require("express");
const router=express.Router();
// middleware specific to admin
router.use(function timeLog (req, res, next) {
console.log('Welcome Admin login at: ', Date.now())
next()
});
router.get('/',(req,res)=>{
console.log("hi sana");
res.status(200).send("hi Sans");
});
module.exports=router;
User route
File Name : user.js
/* user.js */
const express=require('express');
const router=express.Router();
// middleware specific to user
router.use(function timeLog (req, res, next) {
console.log('User login at: ', Date.now())
next()
});
router.get('/',(req,res)=>{
res.status(200).send("hi user");
});
module.exports=router;
Main App
File Name : app.js
/* app.js */
const express=require('express');
const app=express();
const admin=require('./admin');
const user=require('./user');
app.use('/admin',admin);
app.use('/user',user);
app.listen(3000,()=>{ console.log('server running')})
Routing :-
The route file /routes/users.js.
First, it loads the express module and uses it to get an express.Router object. Then it specifies a route on that object and lastly exports the router from the module app.js
File Name :
var express = require('express');
var router = express.Router();
/* GET users listing. */
router.get('/', function(req, res, next) {
res.send('respond with a resource');
});
module.exports = router;
The route defines a callback that will be invoked whenever an HTTP GET request with the correct pattern is matched. The matching pattern is the route specified when the module is
imported ('/users') .
the callback function has the third argument 'next', and is hence a middleware function rather than a simple route callback. While the code doesn't currently use the next argument, it may be useful in the future if you want to add multiple route handlers to the '/' route path.
Previous
Next