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');
url=require('url')
function case1(request,response){ ... }
function case2(request,response){ ... }
http.createServer(function(request, response) {
var q=url.parse(request.url, true).query
switch(true){
case /friend/.test(q):
case1(request,response);
return;
case /foes/.test(q):
case2(request,response);
return;
}
}).listen(9999)
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);
break;
case /\/foes/.test(pathname):
case1(request, response);
break;
}
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);
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments