简体   繁体   中英

Node.js: Server.js is getting cluttered with functions

I have a server.js with many functions.

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?

Thanks

I assume you're using Express? Something I've done in the past is create modules for related handlers. Eg,

Something like this in record-handlers.js :

module.exports = {
    record2: function(req, res) { ... },
    record: function(req, res) { ... }
};

And then in 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.

As you can see here (lines 231 through 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

req.param('action')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM