Processing Query Strings and Form Parameters

HTTP requests often include query strings in the URL or parameter data in the body for form submissions. The query string can be obtained from the URL object defined in the previous section. The parameter data sent by a form request can be read out of the body of the client request, as described later in this chapter.

The query string and form parameters are just basic key/value pairs. To actually consume these values in your Node.js webserver, you need to convert a string into a JavaScript object by using the parse() method from the querystring module:

querystring.parse(str, [sep], [eq], [options])

The str parameter is the query or parameter string. The sep parameter allows you to specify the separator character used; the default separator character is &. The eq parameter allows you to specify the assignment character to use when parsing; the default is =. The options parameter is an object with the property maxKeys that allows you to limit the number of keys the resulting object can contain; the default is 1000, and if you specify 0, there is no limit.

The following is an example of using parse() to parse a query string:

var qstring = require('querystring'),
var params = qstring.parse("name=Brad&color=red&color=blue");
The params object created would be:
{name: 'Brad', color: ['red', 'blue']}

You can also go back the other direction and convert an object to a query string by using the stringify() function:

querystring.stringify(obj, [sep], [eq])

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.15.146.197