Since I am new to Express 4, I will try to make my question as simple as possible. I have been referring to some online tutorials and a confusion has raised.
Normally, the Express 4 setup for app.js has the following type of routes code
.
.
.
var routes = require('./routes/index');
var users = require('./routes/users');
.
.
.
app.use('/', routes);
app.use('/users', users);
I use either Get or Post with whatever parameters, the above works perfect. However, in another tutorial, I see it done differently -like this
.
.
.
var routes = require('./routes’);
.
.
.
app.get('/', routes.index);
app.get('/login', routes.user.login);
.
.
.
I am confused, because normally, I use the app.get method inside the /routes/index.js file OR for anything user related, I use the app.get method in /routes/users.js
Why do we use the app.get directly in the app.js file rather then in the /routes/user.js or /routes/index.js files. Is there any special purpose for doing it this way?
Any help would be highly appreciated. Thanks, in advance.
We all have specific ways that we like to do things. I say this is one of that situations. Only special purpose that I can think of for these types is that some implementations are more suitable for some scenarios.
Example that I have given below is another way of implementing this. I completely move all codes related to routes to another file because I do not need to access router in the app.js
If I want to access router in the app.js , I would have used one of the above implementations.
//We can pass both app, express or just app based on our requirements.
//app.js
require('./app/routes.js')(app, express);
//app/routes.js
module.exports = function(app, express) {
var router = express.Router();
router.route('/users')
.get(function(req,res){
//......
});
app.use('/', router);
};
I hope you got my point.
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.