Tuesday, 2 July 2013

How to list all the parameters passed to a node.js page (in-depth series)

In this tutorial, we will learn how to make use of the data passed to a page in the form of a query string. We will make our server render 2 pages. One will be a form, and the other will be a page that is the action of that form. We will be making use of the url module to deal with URLs. Here is the complete script that will process GET requests. Let us call it forms.js
var http = require('http');
var urlparser = require('url');

// This function will be the one which will be serving
// the webpages. It accepts a request and a response object.
// The request object will contain the query string.
function serve(request, response) {
    response.writeHead(
        200,
        {'Content-Type': 'text/html'}
    );
    var output = "";

    var parsed_url = urlparser.parse(request.url,true);
                     // The second argument is set to true so that the
                     // query string is parsed as well.

    // Render the form if url is /myform
    if(parsed_url.pathname == "/myform"){
        output+="<html><form method='GET' action='/page'>";
        output+="<input type='text' name='name'/><input type='submit'/>";
        output+="</form></html>";
    }

    // Render the page if url is /page
    if(parsed_url.pathname == "/page"){
        var name = parsed_url.query["name"]; // fetch the name
        output+="<html>Hello "+name+"</html>";
    }
    response.end(output);
}

var server = http.createServer(serve);
server.listen(12340);
There, the form is now functional. Run this script from the command line as,
node forms.js
Open up a browser, and visit http://127.0.0.1:12340/myform. Type in jdepths in the text-field and press the Submit Query button. You should see a message like, Hello jdepths.

In this tutorial you also learned how to render different HTML, for different URLs. Hope this was useful. Please do comment to improve the quality of these tutorials.

No comments:

Post a Comment