-
Notifications
You must be signed in to change notification settings - Fork 0
Routes
The routes table is a JSON object that bind regular expressions to functions. The keys in the object are strings written as regular expressions, and the values are functions. (Note that object key can only by of type: string
.) If any incoming requests URL matches a regular expression in the routes table, the related function is called.
We define a regexp for extracting a list of posts in a blog, like this: "^/posts/?$"
. This means any URL of the form: /posts
or /posts/
will match the regex. We define a function to extract all posts from a data store:
var getAllPosts = function(match, req, res) {
/* Code to extract post data */
/* Our function must return data to the client */
res.writeHead(200, {'Content-Type':'application/json'});
res.end(json_string);
};
The defined function is now mapped to a URL in the a route table:
var routes = {
"^/posts/?$" : getAllPosts
};
/* create and start the server */
var server = duality.createServer("/var/www",routes);
Now Duality will automatically call getAllPosts
everytime the request URL matches the regexp. The three arguments passed to the function are a regular expression match
object, and node.js' http.ServerRequest
and http.ServerResponse
objects.
Next we want to get individual blog posts in a RESTful manner like: /posts/[id]
. To do this the function called from the routing table must receive parameters extracted from the regexp. Extracting parameters is done with parenthesis in the regexp, and by quering the match
object. (Please refer to the JS docs on how to do this.) First we add the new function to the routing table:
var routes = {
"^/posts/?$" : getAllPosts,
"^/posts/(\\\n+)" : getPost
};
/* create and start the server */
var server = duality.createServer("/var/www",routes);
First notice the double escaped backslashes. Because Duality will take the string and create a JS RegExp
object from it, it is parsed twice. First when the JS interpreter read your code, second when the RegExp
object initializes from the string. This means you must double escape you characters for the route to work properly.
Now to extract the post id from the URL, we have added the parenthesis around the numeric character wildcard. This will pass the post id to the getPost
function as a part of the match
object. In the function it is easily extracted:
var getPost = function(match, req, res) {
var id = match[1];
/* get the post data for the id */
/* return the post data to the client */
res.writeHead(200,{'Content-Type':'application/json'});
res.end(json_string);
};
Now we can serve blog posts from functions and static files directly from the disk. But often you will need to send the content of a file to the client, from within a route function.
Next, let look at Serving the content of a file.