Search code examples
javascriptnode.jsquery-stringhttpserverquerystringparameter

How do I enforce a check for a particular sequence of parameters in the querystring of an http request handled by a node.js server?


From node.js documentation

querystring.parse('foo=bar&baz=qux&baz=quux&corge')

// returns
{ foo: 'bar', baz: ['qux', 'quux'], corge: '' }

When I parse for the parameters on the server side, is there a way I can check if these parameters are sent in a correct sequence?

For example, I want to enforce that the foo=bar is always the FIRST parameter and so on. How is this achievable?

Right now I can do something like:

var queryData = querystring.parse('foo=bar&baz=qux&baz=quux&corge');

But then doing

if(queryData.foo) {...}

only checks if the parameter 'foo' is present in the url, not if it's in the right place


Solution

  • You can either parse it yourself with something like this:

    var qs = 'foo=bar&baz=qux&baz=quux&corge';
    var parsed = qs.split('&').map(function (keyValue) {
        return keyValue.split('=');
    });
    

    Which will give you something like [ ['foo','bar'], ['baz', 'qux'], ['baz', 'quux'], ['corge', '' ], then you can check if the first is what you want or not: if (parsed[0][0] === 'foo')

    You can also check this question for parsing it yourself: How can I get query string values in JavaScript?

    Or you can rely on the fact that nodejs will insert the property in the same order it was received and v8 will keep the order(which is not really reliable, they might change the behavior): if (Object.keys(queryData)[0] === 'foo').

    Or you can just check if foo is appeared first:

    if (qs.indexOf('foo=') === 0)

    or something like if (qs.slice(0, 4) === 'foo')