How do I handle Express.js routes?

How do I handle Express.js routes?

Problem

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?

Problem courtesy of: Igor Filippov

Solution

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.

Solution courtesy of: NarendraSoni

Discussion

Leave a Reply

Your email address will not be published. Required fields are marked *