Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Express.js Benefits to using Router vs App.use routing?

According to Express documentation, both app.use and Router implement the router interface and can both serve as middleware.

So basically you can define routes by doing

app.use(function (req, res, next) {
  next();
})

or you can also do

var router = express.Router();
router.get('/', function (req, res, next) {
  next();
})
app.use(router);

I was just wondering if there is a reason I would use a router over the app? The only thing I can find on using one or the other is that I need to be consistent with my params. Just curious.

like image 820
aug Avatar asked Oct 20 '22 23:10

aug


1 Answers

Using routes can help organize your code in Express/Node.

This is how I'm using it when I have a specific post request in JSON, but not all requests coming in will be JSON, so I have to parse the JSON only in this instance and subsequently respond:

Using an app on its own:

    app.use("/search", bodyParser.json());
    app.post("/search", function(request, response) {
        params= request.body;
        getSearchResults(params.words, params.numbers, response);
    });

Using an app with a specific router:

    var jsonPostRouter= express.Router();
    jsonPostRouter.use(bodyParser.json())
    jsonPostRouter.use( function(request, response) {
        var params= request.body;
        getSearchResults(params.words, params.numbers, response);
    });

    app.use("/search", jsonPostRouter);

I can then put the router code in a separate module and simply have the app.use("/search", jsonPostRouter); in my main server code, which helps keep my code organized and easier to follow.

like image 197
Megatron Avatar answered Oct 23 '22 04:10

Megatron