Routing with Node.js

   <div>I’m using express web framework. But I don’t need so much feature. I’m using node.js for backend side. I use only for RESTful API. So, I rethink again. Should I use native instead ? Yes, I decided to use native routing. So, What I need to know ? I need to know Regular Expression for match the URL. Oh! that is great. I know regular expression.</div>

>

var sys = require (‘sys’),
url = require(‘url’),
http = require(‘http’);

for declare require. You may see url module. It’s for matching url.

My keyword URL is following

> /keyword/:keyword

so, I wrote regular expression like that

> keyword=//keyword/([A-Za-z0-9]+)$/

Start with /keyword/ and end with A to Z or a to z or 0 to 9. I use ( ) to get the data back.

You can check url like following

>

var url_parts = url.parse(req.url); 
var current_url=url_parts.pathname;

if(current_url.match(keyword)) {
}

Ok. Let see the full source code.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
var sys = require ('sys'),
url = require('url'),
http = require('http'),
qs = require('querystring');
http.createServer(function (req, res) {
keyword=//keyword/([A-Za-z0-9]+)$/
data=//keyword/([A-Za-z0-9]+)/data/([A-Za-z0-9]+)$/;
var url_parts = url.parse(req.url);
var current_url=url_parts.pathname;
if(current_url.match(keyword))
{
result=current_url.match(keyword);
console.log(result);
}
else if(current_url.match(data))
{
result=current_url.match(data);
console.log(result);
}
else
{
console.log(current_url);
}
res.end();
 
}).listen(1337, "127.0.0.1");

Now, you can test it. Open the terminal and call following.

$curl http://localhost:1337
$curl http://localhost:1337/keyword/Hello
$curl http://localhost:1337/keyword/Hello/data/World

comments powered byDisqus