hyprstack
hyprstack

Reputation: 4228

Setting routes in node

I have a module that calculates the area and circumference of a circle. This module has two functions, area and circumference which are calculated based on the value of the radius passed in. In my code I import this module and call it var t. What I'm trying to do is output the value of the area or circumference depending on the value passed to the url. i.e : If the url were to be localhost:8080/circ/4 the page would display "The value of the circumference is + t(4)" AND if the url were to be localhost:8080/area/4 it would display "The value of the area is + t(4)".

I know how to write it using express and hapi, but how would I set the routes using just pure node so that it takes request.params.value where value is the value of the radius? I can't find any examples and most examples use express.

var http = require('http');
var t = require('./modules/myModule.js');


var server = http.createServer();


server.on("request", function(request, response){
    console.log("Request received!");
    response.writeHead (200, {"Content-type": "text/plain"});
    response.write("The value of the circumfrence is ");
    response.end();
  }
);

server.listen(8080);
console.log("Server running on port 8080"); 

Upvotes: 0

Views: 516

Answers (1)

Jasper Woudenberg
Jasper Woudenberg

Reputation: 1166

Out of the box, node doesn't parse params out of your request url, you'll have to do that yourself. One approach would be to use a regular expression to match each route. An example, based on yours, that implements the circ endpoint:

var http = require('http');
var server = http.createServer();

server.on('request', function(request, response){
    // console.log('Request received!');
    var circUrlRegex =/^\/circ\/(\d+)$/;
    var match = circUrlRegex.exec(request.url);
    if (match) {
        var radius = parseInt(match[1], 10);
        var circumference = 2*Math.PI*radius;
        response.writeHead(200, {'Content-type': 'text/plain'});
        response.write('The value of the circumfrence is ' + circumference);
    }
    else {
        response.writeHead(404);
    }
    response.end();
});

server.listen(8080);

Of course if you want to add additional routes, dumping everything into the request event handler quickly becomes unmaintainable. Then you might want to build a system to register routes, and have the handler loop over them one by one until a match is found.

One last thing: you might want to check out Restify. It is a well-supported library for building api's, without all the cruft Express comes with.

Upvotes: 1

Related Questions