Uncategorized

ExpressJS – Configure Routing for Express App

Express is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications.

Express is the most popular Web Framework on Node . So, I planned to write on Express and personally I am a MEAN (Mongo, Express , Angular , Node) Stack fan and MEAN stack became much powerful in Modern Web World.

This article shows how we can configure the routing for an Express app.

var express = require('express');
var app = express();
 
app.get('/'function (req, res) {
	res.send("Home");
});
 
app.get('/profile'function (req, res) {
	res.send("Profile");
});
 
app.get('/contact'function (req, res) {
	res.send("Contact");
});
 
app.get('*'function (req, res) {
	res.send("Not Found" , 404);
});
 
var server = app.listen(3001, function() {
	var host = server.address().address;
	var port = server.address().port;
	console.log('Express app listening at http://%s:%s', host, port);
});

The code is itself self explanatory . I have created 3 Routes and if User hits any other route beside these , Express will return “Not Found” with 404 Status which has been maintained by *

Here we can see server is listening to 3001 port , make sure to use that port which is empty

app takes 2 arguments , first is the route path and second is the callback which would be fired when that Route has been hit by User.

Hope this helps.

Cheers

Standard

Leave a Reply

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