Express js Routing

Express.js provides a way to organize routes. We know each http request has a verb, a URI and HTTP version. It maps an HTTP verb and URI to a request handler.

Example

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

app.get('/user',
function(req, res){
res.send('Welcome user!');
});

app.post('/user',
function(req, res){
res.send('Thanks to visit!');
});

app.listen(3000, function(){ 
	console.log('Server is running at http://localhost:3000');
});

The above example shows logged in user page, it route GET and POST requests to /user page to handle request. We can have multiple HTTP method on the same route.

If we run the above application and open localhost:3030/user on the web browser, we will get the following response.

Express.js Routing

Create a dynamic response

Here, we are taking the parameter value from the url head and echoing the sentence.

var express = require("express");
var app = express();
app.get('/name/:user_name', function(req,res) {
 res.status(200);
 res.set('Content-type', 'text/html');
 res.send('<html><body>' +
 '<h1>Hello ' + req.params.user_name + '</h1>' +
 '</body></html>'
 );
});

app.listen(3000, function(){ 
	console.log('Server is running at http://localhost:3000');
});

Run the above code and open http://localhost:3000/name/smith at the browser.

Router() method

The above code is very tricky in case we have big applications. It will be very difficult to maintain the code. The Express has a router class, by using this we can create many router instances. This creates router as a module.

Syntax

var router = express.Router();

express.Router() essentially creates a new instance of the Express router.

Example

Create a new file of name 'aboutus' and copy paste this code.

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

router.get('/', function(req, res){
   res.send('About Us');
});

module.exports = router;

Then, call the above router module in your main file.

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

var about = require('./about.js');

app.use('/about', about);
app.listen(3000, function(){ 
	console.log('Run at http://localhost:3000/about');
});




Read more articles


General Knowledge



Learn Popular Language