Reputation:
I've generated Express app. I have an index page, I want to add subscribe form for collecting email form the save index page.
So I added a function to ./routes/index.js:
exports.index = function(req, res){
res.render('index', { title: 'Express' });
};
exports.subscribe = function(req, res){
res.send('Subscribed');
};
Here's app.js:
var routes = require('./routes');
//Some code here
app.post('/subscribe', routes.subscribe);
Is that a good way to organise code? I mean, where should I place route handler in such case?
Upvotes: 0
Views: 107
Reputation: 2258
you can do some thing like
app.use(app.router);
var routes = require('./routes')(app);
and then create route.js, which may look like
var index = require('./routes/index');
var users = require('./routes/users');
module.exports = function(app){
app.get('/',index.index);
app.get('/homePage',users.homePage);
};
now as you can see i have created a routes folder to manage all my routes such as index and users. So you can just have a look at the index.js
exports.index = function(req, res){
res.render('index', { title: 'Express' });
};
I mean that's the simplest and you can have get or post as per your requirement. This is the standard which you might see everywhere.
Upvotes: 1