Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

express.Router() vs. app.get

I am using Express 4 server for Node.js

There is a router baked into Express like so:

in app.js

    var router = express.Router();
    app.use(router);
    app.use('/users', usersRoutes);

in userRoutes.js:

var router = express.Router();

router.get('/', function (req, res, next) {

}

router.get('/:user_id', function (req, res, next) {

}

router.post('/:user_id', function (req, res, next) {

}

router.put('/:user_id', function (req, res, next) {

}

router.delete('/:user_id', function (req, res, next) {

}

module.exports = router;

but I am finding it very difficult to find any solid documentation for this type of router online. There is a lot more documentation for the old style of using app.get, app.post, app.put, app.delete, etc. One of the more confusing things is that the first argument (the route path) seems to require that we as programmers strip the app.use argument from the router.get/post/put/delete methods.

For example:

app.use('/users', usersRoutes);

...this means that all the routes in usersRoutes already have an invisible '/users' at the beginning of the paths - something I am not sure I like yet. This means in usersRoutes.js:

 var router = express.Router();

 router.get('/users/:user_id', function (req, res, next) {  //WRONG!!

    }

 router.get('/:user_id', function (req, res, next) {  //RIGHT

    }

This is a bit confusing, but perhaps something I could appreciate with longer paths.

Given the lack of documentation for this express.Router - I assume this is not the preferred way - but is it possible to create a solid RESTful backend with express.Router - and does it have all the basic HTTP verbs attached to it?

Another confusing thing is ----> in app.js we have an instance of router app.use(express.Router()) - how does this router instance interact with the others? Makes little sense on the face of it.

like image 599
Alexander Mills Avatar asked Jun 29 '15 01:06

Alexander Mills


People also ask

What is router () in Express?

The express. Router() function is used to create a new router object. This function is used when you want to create a new router object in your program to handle requests.

What is the difference between Express () and Express router ()?

The main difference is that express() is a top level function, which means it performs core functionality for the library and it contains its own methods where, as a matter of fact, Router is one, and that is why when we create a specific router we chain the Router() method on express , kind of like how we use app.

What is the difference between adding Middlewares using router use () and app use ()?

In short, app. use('/first', router) mounts the middleware at path /first, then router. get sets the subpath accordingly.

What is the difference between app use and app get in Express js?

app. get is called when the HTTP method is set to GET , whereas app. use is called regardless of the HTTP method, and therefore defines a layer which is on top of all the other RESTful types which the express packages gives you access to.

What is the use of app get (*) in Express?

The app. get() function routes the HTTP GET Requests to the path which is being specified with the specified callback functions. Basically it is intended for binding the middleware to your application.


3 Answers

As Bidhan A's answer states, this is preferred way to do it with Express and looks like that since Express 4.

You can completly modulate your code and logic.

For example you can have a routes/APIRouter.js file with this code:

var apiRouter = express.Router();

apiRouter.get('/reports', controllers.getReports);
apiRouter.get('/reports/:id', controllers.getReport);
apiRouter.post('/reports', controllers.createReport);
apiRouter.put('/reports/:id', controllers.updateReport);
apiRouter.delete('/reports/:id', controllers.deleteReport);

Also you could have /controllers/reportsController.js and finally at your main file app.js or also named server.js get:

var express = require('express');
var app = new express();
var apiRouter = require('./routes/APIRouter');
app.use('/api',apiRouter);

So, answering your question:

  1. Yes this is preferred and somehow official way to do it.
  2. Yes, you got whole HTTP to control by using Router and you should use another express based modules like: body-parser, error-handler or cookie-parser in order to complete that control.

Note: this assumes you already know a preferred general web framework directory structure and do module exports.

like image 71
diegoaguilar Avatar answered Oct 08 '22 02:10

diegoaguilar


Great question but nobody should need to ask this question.

The truth is express is an excellent framework. But I have seen so many questions about route handling that we all wasted time. And also even when done correctly, it is just a heap of code that actually wasted people's time writing it and even more in correct stupid errors.

Try Route Magic

You want to do just 2 lines of code and have the module read your directory and file structure to handle all the app.use routing invocations, like this:

const magic = require('express-routemagic')
magic.use(app, __dirname, '[your route directory]')

That's really it! Nothing else.

For those you want to handle manually, just don't use pass the directory to Magic.

Say goodbye to

app.use('/i/repeat/myself', require('./routes/i/repeat/myself'))
app.use('/i/repeat/myself/again', require('./routes//i/repeat/myself/again'))
app.use('/i/keep/repeating/myself', require('./routes/i/keep/repeating/myself'))
like image 31
Calvintwr Avatar answered Oct 08 '22 01:10

Calvintwr


Express().get does the same as Express.Router().get. The difference is that router is better practice because it allows us to manage api endpoints as a middleware.

https://expressjs.com/en/api.html#router

The problem with Express and JS frameworks like it is that the documentation doesn't explain why the shift from using the Express main "app" object. My guess is that we should separate concerns from the logic of routes from the main application management itself (ie. configuration, template, database connection, etc.)

like image 43
Cyrus Talladen Avatar answered Oct 08 '22 03:10

Cyrus Talladen