Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between app.get() or router.get() - ExpressJs

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() {

    .....
    })
like image 813
Morris Avatar asked Jan 24 '17 18:01

Morris


2 Answers

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.

like image 64
Explosion Pills Avatar answered Oct 16 '22 12:10

Explosion Pills


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.

like image 4
Jeet Avatar answered Oct 16 '22 14:10

Jeet