简体   繁体   中英

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.

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.

I actually think that this is in fact the preferred way. You define your routes separately and simply use it in your app. It provides a nice separation of concerns. It also makes testing your routes quite easy. And yes, you can create a solid RESTful backend using express.Router. Also, it has all the basic HTTP verbs like get, post, put, delete, patch etc. attached to it.

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.)

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'))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM