[英]Node.js: Server.js is getting cluttered with functions
I have a server.js
with many functions. 我有一个具有许多功能的
server.js
。
app.post '/record2', (req,res) ->
app.post '/record', (req,res) ->
app.post '/incoming', (req,res) ->
app.post '/call', (req,res) ->
etc..
It's starting to become very confusing. 它开始变得非常混乱。 What's the best way to make the server.js cleaner and easier to understand?
什么是使server.js更加整洁和易于理解的最佳方法?
Thanks 谢谢
I assume you're using Express? 我认为您正在使用Express? Something I've done in the past is create modules for related handlers.
我过去做过的事情是为相关处理程序创建模块。 Eg,
例如,
Something like this in record-handlers.js
: 在
record-handlers.js
:
module.exports = {
record2: function(req, res) { ... },
record: function(req, res) { ... }
};
And then in server.js
: 然后在
server.js
:
var recordHandlers = require('./record-handlers');
app.post('/record2', recordHandlers.record2);
app.post('/record', recordHandlers.record);
...
*My apologies for converting your Coffeescript to JS - I don't know CS at all. *很抱歉将您的Coffeescript转换为JS-我一点也不了解CS。
As you can see here (lines 231 through 235.) 正如你可以看到这里 (线231通过235)
switch (config.method) {
case 'GET': server.get(config.path, internals.preprocessRequest, routes, config.handler, internals.finalizeResponse); break;
case 'POST': server.post(config.path, internals.preprocessRequest, routes, config.handler, internals.finalizeResponse); break;
default: process.exit(1); break;
}
the routes and the handlers are in different modules. 路线和处理程序位于不同的模块中。
Another strategy would be to use a catch-all route like this : 另一种策略是使用像这样的包罗万象的路线:
/:action
and use a switch statement to call the required function based on the value of 然后使用switch语句根据的值调用所需的函数
req.param('action')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.