What is the difference between:
var express = new express();
var app = new express();
app.get("/", function() {
.....
})
And:
var express = new express();
var router= express.Router();
router.get("/", function() {
.....
})
app.get
can be used to create routes for your application at the top level.
From the documentation about express.Router
Use the express.Router class to create modular, mountable route handlers. A Router instance is a complete middleware and routing system; for this reason, it is often referred to as a “mini-app”.
A router needs to be mounted to an app:
const router = express.Router();
router.get("/", (res, req) => res.end());
router.post("/", (res, req) => res.end());
app.use("/empty", router);
This allows you to more easily encapsulate the functionality of several routes into an app which will be namespaced under a particular route.
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.
Check this SO Thread for details.
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