NodeJs Tutorials
- NodeJs
- Install NodeJs
- Why use NodeJs
- NodeJs Process Model
- create First Application
- Run NodeJs Application
- Node.js Console
- Node.Js Modules
- URL Modules
- node.js Callback
- Node.js Events
- Upload Files
- Upload single & Multiple Files
- NodeJs File System
- NodeJs Email
- Debugging NodeJs
- .ENV
- NodeJs Mysql
- Helpers
- encription and decription in nodeJs
- Query string
- Date & Time
- Express Js
- Template Engine with Express
- MVC Pattern in Node.Js
- list of NPM Module
- Middleware
- Body Parser
- Render
- Nodemon module
- Morgan module
- Flash Message in ExpressJs
- Session
- Session store in database
- Cookies
- Helmet
- Multer
- Router: How To Use Routing In Node.Js
- App.Js
- express.json() and express.urlencoded()
- REST APIs in NodeJs
- Gloabal Objects
- Submit Form Data
- How to get Post Data in Node.js
- How to Get URL Parameters in Node.js
- How to create Node Project
- How to Insert Form Data Into the MySql Table Using Node.js
- How to fetch Data from MySQL database table using Node.js
- CRUD Example
- Await and Async
- Promises
- Login Example
- Password Encription
- How to validate Form (Form Validation) in Node.Js?
- Registration & Login form usingn Node.Js & MySql?
- Forgot & Reset Password
- File Upload in Node.Js with ExpressJs
- Resize Image Before Upload using Multer Sharp
- Upload multiple file using node.js with multer module
- Upload file using node.js with multer module
- Client IP Address
- REST API Downloading File in NodeJs
- Export and Download CSV From MySQL Database
- CRUD REST API
- CRUD REST API Example 2
- Enable HTTPS using Node
- How to send EMAIL using NodeJs?
- Dynamic dependent dropdown using NodeJs?
- Autocomplete Search
- Get and Send Data From Ajax Request
- Get and Post Data using Ajax
- Passport Authentication
- Node Js Data type
- Node Js Error
- Node Js Array Function
- Node Js String Function
- Puppeter Module
How To Use 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 :-
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.
File Name :
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;
File Name :
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.
File Name :
File Name :
File Name :
File Name :