express.Router() vs. app.get
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.)
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:
- Yes this is preferred and somehow official way to do it.
- Yes, you got whole HTTP to control by using
Router
and you should use another express based modules like:body-parser
,error-handler
orcookie-parser
in order to complete that control.
Note: this assumes you already know a preferred general web framework directory structure and do module exports.