JulienFr JulienFr - 1 year ago 61
Node.js Question

How do you use several request handler in node.js?

I come from tornado, where you have a requestHandler class and you match the query to orient it to the right requestHandler.

How do you do in node.js? Something like that ????

http=require ('http');

function case1(request,response){ ... }

function case2(request,response){ ... }

http.createServer(function(request, response) {
var q=url.parse(request.url, true).query
case /friend/.test(q):
case /foes/.test(q):

Answer Source

With Node.js' http.Server, you're on your own for establishing any routing.

And, you're close to this. Though, you'll want to test based on the parsed URL's pathname rather than query.

var pathname = url.parse(request.url, true).pathname;

switch (true) {
    case /\/friend/.test(pathname):
        case1(request, response);

    case /\/foes/.test(pathname):
        case1(request, response);

You'll probably also want to include testing the request.method.

case request.method === 'GET' && /\/friend/.test(pathname):

Or, as soulcheck mentioned, there are numerous libraries/framework available that have an established API for routing, including express and restify.

var app = express();

app.get('/friend', case1);
app.get('/foes', case2);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download