nelson687 nelson687 - 3 months ago 9
Node.js Question

Differences between express.Router and app.get?

I'm starting with

Express 4
, and I'm a bit confused. I been reading the
website, but can't see _when to use a route handler or when to use

As I could see, if I want to show a page or something when the user hits
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
, is that right or this is the way for

If this is the way to do it in
, what is
used for?

I read almost the same example as above but using

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?



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);



var express = require('express');

var router = express.Router();

router.get('/', function(req, res) {
    res.send('GET handler for /dogs route.');
});'/', 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.