pittuzzo
pittuzzo

Reputation: 491

Nodejs Express: Routes in separate files

I write my app.js including all the routes in the main file and everything was working well. After my goal was to make the project more clear by moving the routes in a different files but it is not working. I'm passing an object instead of a middleware function and I don't know how to fix it in the right way.

So this is my app.js file:

var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var morgan = require('morgan');
var mongoose = require('mongoose');
var myRoutes = require('./app/routes/myRoutes.js');

...

//parser for getting info from POST and/or URL parameters
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

//for log requests to console
app.use(morgan('dev'));

app.use('/myRoutes', myRoutes);

app.get('/',function(req,res){
    res.end('Welcome Page!');
});

//Server Start
app.listen(port);
console.log('server start at port ' + port);

And the app/routes/myRoutes.js contains the following code:

var express = require('express');
...
var myRoutes = express.Router();

myRoutes.get('/users',function(req,res){
...
});

myRoutes.post('/setup',function(req,res){
    ...
});

myRoutes.post('/remove', function(req,res){
    ...
});

module.export = myRoutes;

I also tried this:

var express = require('express');
var myRoutes = express.Router();

myRoutes.route('/')
    .get(function(req, res, next){
        res.end('myRoute Get');
    })
    .post(function(req, res, next){
        res.end('myRoute Post');
    });

module.export = myRoutes;

But again it seems not passing a middleware function.

Upvotes: 3

Views: 820

Answers (2)

georoot
georoot

Reputation: 3617

Hi this is more of additional tips on the question. You main js file would definately need to load a lot of routes and i found importing all of them is a lot of work. Rather use require-dir module to load all the routes like

const loader = require('require-dir');
var app = express();
var routes = loader('./routes');
for (route in routes){
  app.use("/"+route,routes[route]);
}

needless to say define all routes inside routes folder and export Router module in each one of them like

var router = express.Router();

router.get(....);

module.exports = router; 

Upvotes: 0

pittuzzo
pittuzzo

Reputation: 491

My second option code

var express = require('express');
var myRoutes = express.Router();

myRoutes.route('/')
    .get(function(req, res, next){
        res.end('myRoute Get');
    })
    .post(function(req, res, next){
        res.end('myRoute Post');
    });

module.export = myRoutes;

is working fine! I just write it in a wrong way

module.export = myRoutes;

isntead of

module.exports = myRoutes;

Upvotes: 2

Related Questions