Monday, 23 April 2018

How to implement routing in Nodejs

A route is a mapping from a url to an object.It handles HTTP client requests.

Basic Routing

Hope you have install and have basic knowledge Express module.
npm install express

Note: Above command download the required express modules and install them.

Here is our Server file.

var express = require( 'express' );
var app = express();
//Creating Router() object
var router = express.Router();
// Provide all routes here, this is for Home page.
router.get("/",function(req,res){
  res.json({"message" : "Hello World"});
});
app.use("/",router);
// Listen to this Port
app.listen(3000,function(){
  console.log("Live at Port 3000");
});

Code Explanation:

1. In our first line of code, include the "express module."
2. Create object of the express module.
3. Creating a callback function. This function call when you hit url from browser http://localhost:3000 .It send the string 'Hello World' to the web page.
4. The 'res' parameter is used to send content back to the web page.
5. Create object of route() module. And handle get request.

Basic middleware routing :

// Router middleware, mentioned it before defining routes.

router.use(function(req,res,next) {
  console.log("/" + req.method);
  next();
});

Create a router file named route.js in the app directory, with the following content:

var express = require('express')
var router = express.Router()

// middleware that is specific to this router
router.use(function timeLog (req, res, next) {
  console.log('Time: ', Date.now())
  next()
})
// define the home page route
router.get('/', function (req, res) {
  res.send('Home page content')
})
// define the about route
router.get('/about', function (req, res) {
  res.send('About page content')
})
module.exports = router

Load the router module in the app:

var routes = require('./route');
app.use('/child', routes)

Now make a requests to /child and /child/about

0 comments:

Post a Comment