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.
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.
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.
In short, app. use('/first', router) mounts the middleware at path /first, then router. get sets the subpath accordingly.
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.
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.
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:
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.
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.
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'))
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.)
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