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.