require('express')() vs. require('express').Router()

107 views
Skip to first unread message

Ricardo Ferro

unread,
Jul 27, 2014, 2:06:06 PM7/27/14
to expre...@googlegroups.com
Hi all,

what differences using both? The result is the same?

express()

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

one.get("/", function(req, res) {
  res.send('hello');
});

app.use("/one", one);

express.Router()

var express = require('express');
var app     = express();
var one     = express.Router();

one.get("/", function(req, res) {
  res.send('hello');
});

app.use("/one", one);


tks
Ricardo Ferro

Angel Java Lopez

unread,
Jul 27, 2014, 3:28:36 PM7/27/14
to expre...@googlegroups.com
My first use:

Your router define the URLs, but the URL prefix is defined at app.

So, one module could return a router, and your top app decides where to expose the result

I don't know yet, if the router could define the template engine to use inside the router. So your app could compose different routers, written by different programmers, even with other templates

Angel "Java" Lopez
@ajlopez




Ricardo Ferro

--
You received this message because you are subscribed to the Google Groups "Express" group.
To unsubscribe from this group and stop receiving emails from it, send an email to express-js+...@googlegroups.com.
To post to this group, send email to expre...@googlegroups.com.
Visit this group at http://groups.google.com/group/express-js.
For more options, visit https://groups.google.com/d/optout.

greelgorke

unread,
Jul 28, 2014, 4:39:40 AM7/28/14
to expre...@googlegroups.com
they are not the same.

in the first case you define two different express apps, which can have their own set of settings, templates (and engine), middleware and routes. 'app' mounts 'one' as sub-app, but 'one' could be used as the main app itself.

the second case you have only one app, and you have defined a set of routes on one router. in express 4, the Router is visible and can be instantiated several times, i.E. to bundle routes in an app logically. but they do not have separated settings, they are plugged in the same middleware chain. so in your second example you did nothing else than to define one single route: 'GET /one/'

the first approach is usefull when your web application is highly modular and got assembled at configuration time. Every sub-app can be developed as stand-alon app, with its oun templating and routing and even own middlewares, and be even deployed as dependency via npm. the second approach is the defaul wy to defin routes in express 4 and you can use several Router instances to group routes logicaly, i.E. per resource or per access restrictions. it makes it easier to define middlewares specific to a group of routes this way.
Reply all
Reply to author
Forward
0 new messages