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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With