nelson687 nelson687 - 4 months ago 10
Node.js Question

Differences between express.Router and app.get?

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.Router
.

As I could see, if I want to show a page or something when the user hits
/show
for example I should use:

var express = require('express')
var app = express()
app.get("/show", someFunction)


At the beginning, I thought this was old, for
express3
, is that right or this is the way for
express4
too?

If this is the way to do it in
express4
, what is
express.Router
used for?

I read almost the same example as above but using
express.Router
:

var express = require('express');
var router = express.Router();
router.get("/show", someFunction)


So, what's the difference between both examples?

Which one should I use if I just want to do a simple testing website?

Answer

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 express() is called in app.js, an app object is returned. Think of an app object as an Express application.

When express.Router() is called, a slightly different "mini app" is returned. The idea behind the "mini app" is that different routes in your app can become quite complicated, and you'd benefit from moving that logic into a separate file.

In this simple example above, the logic for the /dogs route has been moved into its own file just so its GET and POST handlers won't clutter up app.js. Now you can work on the logic for any requests to /dogs in isolation and not worry about how it will affect /cats and /birds.

If you have logic (called middleware in Express) that pertains to all three routes, you can put it in app.js above the app.use(...) calls. If you have logic that pertains to just one of those routes (/dogs), then you put it in the file for that route only.

Comments