[英]How do I split up index.js file in a node/mean/express application?
I've got one incredibly long index.js route file for my node/mongo/express application. 我的node / mongo / express应用程序有一个非常长的index.js路由文件。 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? 如何分割index.js文件?
For example, I have tried to do something like this in my app.js file 例如,我试图在我的app.js文件中做类似的事情
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. 但是,它找不到我只有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?
这可能是因为我从route / index.js中提取了所有以“ / task”开头的路由,并将它们放置在route / task.js中,但是为什么在这个新文件中表达出无法识别这些路由?
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. 任何建议都将是有帮助的,我和我的朋友对整个meanjs的工作方式还很陌生,并且基本上将各种教程中的内容拼凑在一起。 Now we desperately need to refactor, because routes/index.js is getting too long to work with.
现在我们迫切需要重构,因为route / index.js的使用时间太长了。 I did my best to do what makes sense intuitively, could anyone out there give advice on how to break up our routes file?
我尽力做到直观上有意义的事情,在那里有人可以提供有关如何分解我们的路线文件的建议吗?
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. 这些文件中的每个文件都应执行
module.exports
并带有路由器对象或类似的东西,可以在您创建的应用程序实例上挂载路由。
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. 例如,看看我是怎么做的(与自耕农的帮助这是)一个项目,我有GitHub上这里 ,则是指路由器对象如何导出像每个路由这个例子。
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 .
请注意,我们有一个稍微类似的做法在这里 ,再看看一个例子航线声明(包括相应的出口) 这里 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.