Warning: include(sidebar-express.html): failed to open stream: No such file or directory in /home/javavill/public_html/datastapler.com/add-router-to-express-js-application.php on line 19

Warning: include(): Failed opening 'sidebar-express.html' for inclusion (include_path='.:/usr/lib/php:/usr/local/lib/php') in /home/javavill/public_html/datastapler.com/add-router-to-express-js-application.php on line 19

Add router to ExpressJS Application

Before adding router to Express Js generator application; Need to know each folder details and where to add entries to make one more router available.

Router: Routing refers to the definition of end points (URIs) to an application and how it responds to client requests.

Currently after generating express application, using express-generator we have two routers existed. Will add one more to understand the system.

Create one more router inside routes folder as abdc.js. This example explains you, how one route can be handled using an array of callback functions

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

	var cb0 = function (req, res, next) {
	var cb1 = function (req, res, next) {
	router.get('/', [cb0, cb1], function (req, res, next) {
		console.log('response will be sent by the next function ...');
	}, function (req, res) {
		res.send('respond with a resource111111111111');
	module.exports = router;

From above router :

express.Router: The express.Router class can be used to create modular mountable route handlers. A Router instance is a complete middleware and routing systemÍž for this reason it is often referred to as a "miniapp".

module.exports = router; The example creates a router as a module, loads a middleware in it, defines some routes, and mounts it on a path on the main app.

router need be added for module.exports(module.exports = router;), then only that router will be available.

Add below line in app.js after app.use('/users', users);

var abcd = require('./routes/abcd');

Add below line in app.js after users variable.

var abcd = require('./routes/abcd');

The app directory structure looks like the following.

Extra router Express App wokspace

Do install once again

npm install

Once done with succesfull install, use below command to start application

npm start

Then hit this url http://localhost:3000/ in browser to access the app.

Express generator result