Introduction to Routing in express js

Express has some built-in service layer, express handle the service requests using routing. The routing in Express maps HTTP verbs plus URI combo to an ask for the handler function. The routes are the application endpoint URI or path and HTTP request method (GET, POST, HEAD, PUT, DELETE ) and how the endpoint responds to a client request. In the example below, we displaying the different messages with routing to a specific URL in the express.

var express = require("express")
var app = express();

app.get("/", function(req, res){
	res.send("Welcome to Home page");
});

app.get("/tamo", function(req, res){
	res.send("Welcome to tamo page");
});

app.use(function(req, res){
	res.status(404).send("Page not found");
});

app.listen(3000)

When we make professional node apps, then we have to use standard routing. We will create a separate folder for the routes, views, and static files as public in the app folder. All the route codes kept in the routes folder.  Example index.js for the home page route and feedback .js for feedback page route.

Step1: Add the following code in app/app.js and we will have to add the corresponding view for the home page.

var express = require('express');
var app = express();

app.set('port', process.env.PORT || 3000); 
app.set('view engine', 'ejs');
app.set('views', 'app/views');


app.use(express.static('app/public'));
app.use(require('./routes/index'));
app.use(require('./routes/teachers'));
;

var server = app.listen(app.get('port'), function(){
    console.log('Listening on port' + app.get('port'));
});

reload(server, app);

Add the following code in app/routes/index.js to route to a home page and we will have to create the corresponding view for the home page.

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

router.get('/', function(req, res){
    res.render('index',{
        pageTitle: 'Home',
        pageID: 'home'
    });
});

module.exports = router; 

Add the following code in app/routes/teacher.js to route to URL localhost/teacher and /teacher/id and we will have to create the corresponding view for both teachers and teacher/id route. Express allows us to specify our routes as a string and to specify them as regular expressions.

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


var ALLOWED_IPS = [
    "127.0.0.1",
    "10.10.10.1",
    "localhost"
];

router.use(function(req, res, next){
    var userIsAllowed = ALLOWED_IPS.indexOf(req.ip) !== -1;
    if(!userIsAllowed){
        res.status(401).send("Not Authorized !");
    }else{
        nex();
    }
});


router.get('/teachers', function(req, res) {
  res.render('teachers', {
    pageTitle: 'Teachers',
    pageID: 'teacherList'
  });
});

router.get('/teachers/:teacherid', function(req, res) {
  data.speakers.forEach(function(item) {
    if (item.shortname == req.params.speakerid) {
      pageSpeakers.push(item);
      pagePhotos = pagePhotos.concat(item.artwork);
    }
  });

  res.render('teachers', {
    pageTitle: 'Teacher Info',
    pageID: 'teacherDetail'
  });
});

router.get('/teacher/message', function(req, res) {
  res.render('users', {
    pageTitle: 'message',
    pageID: 'messageDetail'
  });
});
module.exports = router;

Using Express with HTTPS

We can add the https to our Node apps. The express use built-in HTTPS module for HTTPS access and we have to supply certification key and the private key in Node to access our web HTTPS protocol. Simple example node apps with both HTTP and HTTPS

Example: Express apps with both HTTP and HTTPS

var https = require("https");
var fs = require("fs");

var app = express();

var httpsOptions = {
	key: fs.readFileSync("path/to/private/key.pem");
	cert: fs.readFileSync("path/to/certificate.pem")
};
http.createServer(app).listen(80);
https.createServer(httpsOptions, app).listen(443);

Express has some built-in service layer, express handle the service requests using routing. The routing in Express maps HTTP verbs plus URI combo to an ask for the handler function. The routes are the application endpoint URI or path and HTTP request method (GET, POST, HEAD, PUT, DELETE ) and how the endpoint responds to a client request. In the example below, we displaying the different messages with routing to a specific URL in the express.

var express = require("express")
var app = express();

app.get("/", function(req, res){
	res.send("Welcome to Home page");
});

app.get("/tamo", function(req, res){
	res.send("Welcome to tamo page");
});

app.use(function(req, res){
	res.status(404).send("Page not found");
});

app.listen(3000)

When we make professional node apps, then we have to use standard routing. We will create a separate folder for the routes, views, and static files as public in the app folder. All the route codes kept in the routes folder.  Example index.js for the home page route and feedback .js for feedback page route.

Step1: Add the following code in app/app.js and we will have to add the corresponding view for the home page.

var express = require('express');
var app = express();

app.set('port', process.env.PORT || 3000); 
app.set('view engine', 'ejs');
app.set('views', 'app/views');


app.use(express.static('app/public'));
app.use(require('./routes/index'));
app.use(require('./routes/teachers'));
;

var server = app.listen(app.get('port'), function(){
    console.log('Listening on port' + app.get('port'));
});

reload(server, app);

Add the following code in app/routes/index.js to route to a home page and we will have to create the corresponding view for the home page.

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

router.get('/', function(req, res){
    res.render('index',{
        pageTitle: 'Home',
        pageID: 'home'
    });
});

module.exports = router; 

Add the following code in app/routes/teacher.js to route to URL localhost/teacher and /teacher/id and we will have to create the corresponding view for both teachers and teacher/id route. Express allows us to specify our routes as a string and to specify them as regular expressions.

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


var ALLOWED_IPS = [
    "127.0.0.1",
    "10.10.10.1",
    "localhost"
];

router.use(function(req, res, next){
    var userIsAllowed = ALLOWED_IPS.indexOf(req.ip) !== -1;
    if(!userIsAllowed){
        res.status(401).send("Not Authorized !");
    }else{
        nex();
    }
});


router.get('/teachers', function(req, res) {
  res.render('teachers', {
    pageTitle: 'Teachers',
    pageID: 'teacherList'
  });
});

router.get('/teachers/:teacherid', function(req, res) {
  data.speakers.forEach(function(item) {
    if (item.shortname == req.params.speakerid) {
      pageSpeakers.push(item);
      pagePhotos = pagePhotos.concat(item.artwork);
    }
  });

  res.render('teachers', {
    pageTitle: 'Teacher Info',
    pageID: 'teacherDetail'
  });
});

router.get('/teacher/message', function(req, res) {
  res.render('users', {
    pageTitle: 'message',
    pageID: 'messageDetail'
  });
});
module.exports = router;

Using Express with HTTPS

We can add the https to our Node apps. The express use built-in HTTPS module for HTTPS access and we have to supply certification key and the private key in Node to access our web HTTPS protocol. Simple example node apps with both HTTP and HTTPS

Example: Express apps with both HTTP and HTTPS

var https = require("https");
var fs = require("fs");

var app = express();

var httpsOptions = {
	key: fs.readFileSync("path/to/private/key.pem");
	cert: fs.readFileSync("path/to/certificate.pem")
};
http.createServer(app).listen(80);
https.createServer(httpsOptions, app).listen(443);

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top