Reputation: 13972
I've got one incredibly long index.js route file for my node/mongo/express application. Here is the structure.
app.js
/models
Schedule.js
Task.js
etc...
/routes
index.js
/public
/javascript
etc...
I want something like this
app.js
/models
Schedule.js
Task.js
etc...
/routes
index.js
schedule.js
tasks.js
etc...
/public
/javascript
etc...
How can I split up my index.js file?
For example, I have tried to do something like this in my app.js file
var routes = require('./routes/index');
var tasks = require('./routes/tasks');
// later in the file
app.use('/', routes);
app.use('/tasks', tasks);
However, it is not finding my task routes like it did before when I had only the index.js. This is probably because I took all the routes starting with "/task" from my routes/index.js and placed them in routes/task.js, but why express not recognizing the routes in this new file?
Any advice at all would be helpful, my friend and I are very new to the whole meanjs way of doing things, and basically cobbled together what we have from various tutorials. Now we desperately need to refactor, because routes/index.js is getting too long to work with. I did my best to do what makes sense intuitively, could anyone out there give advice on how to break up our routes file?
Upvotes: 0
Views: 1725
Reputation: 871
Well, the answer to this question lies in how you import (require in this context) the router instance. Each one of those files should do a module.exports
with a router object or something similar where the routes can be mounted on the app instance you create.
For example, have a look at how I do it (with yeoman's help that is) in a project I have on GitHub here, then refer to how the router object is exported for each route like this example.
As another example of doing this, here is an open source project I've been contributing to here. Notice that we have a slightly similar approach here, then have a look at an example route declaration (with the corresponding export) here.
Upvotes: 1