How do I handle Express.js routes?

How do I handle Express.js routes?


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){

Here’s app.js:

var routes = require('./routes');
//Some code here'/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


you can do some thing like

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){

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


Leave a Reply

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