I\'m starting with NodeJS and Express 4, and I\'m a bit confused. I been reading the Express website, but can\'t see when to use a route handler or when to use
Express 4.0 comes with the new Router. As mentioned on the site:
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 “mini-app”.
There is a good article at https://scotch.io/tutorials/learn-to-use-the-new-router-in-expressjs-4 which describes the differences and what can be done with routers.
To summarize
With routers you can modularize your code more easily. You can use routers as:
- Basic Routes: Home, About
- Route Middleware to log requests to the console
- Route with Parameters
- Route Middleware for Parameters to validate specific parameters
- Validates a parameter passed to a certain route
Note:
The app.router
object, which was removed in Express 4, has made a comeback in Express 5. In the new version, it is a just a reference to the base Express router, unlike in Express 3, where an app had to explicitly load it.
app.js
var express = require('express'),
dogs = require('./routes/dogs'),
cats = require('./routes/cats'),
birds = require('./routes/birds');
var app = express();
app.use('/dogs', dogs);
app.use('/cats', cats);
app.use('/birds', birds);
app.listen(3000);
dogs.js
var express = require('express');
var router = express.Router();
router.get('/', function(req, res) {
res.send('GET handler for /dogs route.');
});
router.post('/', function(req, res) {
res.send('POST handler for /dogs route.');
});
module.exports = router;
When var app = express()
is called, an app object is returned. Think of this as the main app.
When var router = express.Router()
is called, a slightly different mini app is returned. The idea behind the mini app is that each route in your app can become quite complicated, and you'd benefit from moving all that code into a separate file. Each file's router becomes a mini app, which has a very similar structure to the main app.
In the example above, the code for the /dogs route has been moved into its own file so it doesn't clutter up the main app. The code for /cats and /birds would be structured similarly in their own files. By separating this code into three mini apps, you can work on the logic for each one in isolation, and not worry about how it will affect the other two.
If you have code (middleware) that pertains to all three routes, you can put it in the main app, before the app.use(...)
calls. If you have code (middleware) that pertains to just one of those routes, you can put it in the file for that route only.
In one of the questions in the quiz this was asked: "express.Router()
creates an object that behaves similar to the app object."
The correct answer is 'True'. I know that we can both create routers by using either of the two but is it safe to say that they are not the same in all cases? If my understanding is correct, the express()
variable can do more things like start a server while the other one cannot.
Let’s say your application is little complex. So what we do first is we divide the application into multiple modules so that changes in one module doesn't clutter the others and you can keep working on individual modules, but at the end of the day you need to integrate everything into one since you are building a single application. It is like we have one main application and few child applications whose parent is the main application. So when we create the parent application we create one using
var express = require('express');
var parent = express();
And to this parent application we need to bring in the child applications. But since the child applications are not totally different applications(since they run in the same context-java term), express provides the way to do it by means on the Expresse's Router function and this is what we do in the each child module file and lets call one such child module as aboutme.
var express = require('express');
var router = express.Router();
/**
** do something here
**/
module.exports = router;
By module.exports we are making this module available for other to consume and since we have modularized things we need to make the module files available to the parent application by means of node's require function just like any other third party modules and the parent file looks something like this.
var express = require('express')
var parent = express()
var child = require(./aboutme)
after we make this child module available to the parent we need to tell the parent application when to use this child application. Lets say when a user hits the path aboutme we need the child application about me to handle the request and we do it by using the Expresse's use method.
parent.use('/aboutme', aboutme);
and in one shot the parent file looks like this
var express = require('express');
var parent = express();
var child = require(./aboutme);
/***
**do some stuff here
**/
parent.use('/aboutme',child);
Above all what the parent can do is it can start a server where as the child cannot. Hope this clarifies. For more information you can always look at the source code which takes some time but it gives you a lot of information. Thank you.
app.route('/book')
.get(function (req, res) {
res.send('Get a random book')
})
.post(function (req, res) {
res.send('Post a random book')
})
As in above example, we can add different HTTP request method under a route.
using app.js to write routes means that they are accessible to all the users as app.js is loaded on application start. However, putting routes in express.router() mini apps protect and restrict their accessibility.