how to get the Id from the URL while using node.js


Question

I am quite new to Javascript and node.js and I'm trying to create a REST API, and the urls will be of the form.

  1. /user/{userId}/docs

I am trying to get the value of {userId}, which in the case of /user/5/docs will be 5.

I could try to pass this as a request parameter(in the querystring or in the body, depending on the GET or POST method), but the url looks more intuitive when it is formed this will. Plus there are many more urls which are like these.

I am wondering if there are any node modules like express which provide for this.

I am a traditional Java user and Jersey framework used to provide such a thing in Java.

Thanks, Tuco

1
15
8/28/2012 9:35:38 PM

Accepted Answer

Spend some time with the documentation. Express uses the : to denote a variable in a route:

app.get('/user/:id/docs', function(req, res) {
    var id = req.params.id;
});
64
8/28/2012 2:03:54 PM

Write the following in the server script:

var http = require('http');
var server = http.createServer(function (request, response) {
    var url = request.url; //this will be /user/5/docs
    url.id = url.split("/")[2]; // this will be 5
    response.writeHead(200, {'Content-Type' : 'text/html'});
    response.end("Id is = " + url.id);
});
server.listen(8000, '127.0.0.1');

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon