Home > Blockchain >  What is the difference between the two calls to express()
What is the difference between the two calls to express()

Time:04-20

I have 2 require('express) calls. First:

const express = require('express');
const app = express();

Second:

const Router = require('express');
const router = new Router();

What is the difference, why in the first we call a function, and in the second we create an object, if the methods are the same in both (use, get, post, etc)?

CodePudding user response:

Your second call is incorrect, you are just calling (requiring) express which is similar to your first call.

I never did const router = new Router();, so I'm not sure what that accomplish.

I generally do-

const router = require('express').Router();
router.get();

Even though with your first call you can do

app.get() and app.post()

According to express explanation

express.Router class is used to create modular, mountable route handlers. A Router instance is a complete middleware and routing system

Read more about it here

GeekforGeeks explains express.Router() very well

CodePudding user response:

I think your question missed something. Your second example shows this:

const Router = require('express');

... but I think you meant to do this:

const Router = require('express').Router;

... regardless, the following should help you better understand.

In express, you can think of Routers as little mini applications... lightweight express apps... which have their own routing. In fact, the main "express" object is itself a Router. For example, you might have a bunch of endpoints for managing users:

// ./routes/user-routes.js
const userRoutes = new express.Router();
userRoutes.get('/', getAllUsers);
userRoutes.get('/:userId', getUserById);
userRoutes.post('/', createUser);
userRoutes.put('/:id', updateUser);
userRoutes.delete('/:id', removeUser);

Notice how none of the urls have anything like /users/ inside them. This is important because this little mini app can now be "mounted" (for lack of better terms) in a larger express app like follows:

const express = require('espress');
const userRoutes = require('./routes/user-routes');

const app = express();
app.use('/path/to/users', userRoutes);

Notice how the userRoutes were "mounted" on the /path/to/users such that all user requests will happen to the following URLs:

  • GET /path/to/users - get all users
  • GET /path/to/users/1234 - get user with id "1234"
  • ... you get the point

This is mostly a convenient way to think about your app as a bunch of smaller mini apps which are orchestrated together.

  • Related