Checking URL Query String in Node.js

A well-formed query string looks like this:

http://baseurl.thing/update?id=123&foo=50&bar20

I want to map this “safely” to an object, but I don't want the result to be undefined values. Is there a good way to check the query string?

Details: I want to turn this into an object with a module url. i.e:.

var url_parts = url.parse(request.url, true);

and then I can route based url_parts.pathname. I want to access url_parts.query.id, url_parts.query.fooand url_parts.query.bar, but only if they all exist, and only if no other parameters have been provided, so that I don't fade out the undefined values.

+3
source share
1 answer

set the default values ​​and then rewrite them with the values ​​from your URL.

Example

var defaults = {
    id : 0,
    foo : 'default value',
    bar : 'default.value'
};

var url_parts = url.parse(request.url, true);
var query = url_parts.query;
query.prototype = defaults; //does the inheritance of defaults thing
// now query has all values set, even if they didn't get passed in.

Hope this helps!

+6
source

Source: https://habr.com/ru/post/1787485/


All Articles