3

I need to edit a node.js app GET a querystring, without (i) using Express or any other modules and (ii) creating a server in addition to the one which already exists.

I want to pass ?id=helloworld into the variable id.

How would I do this?

1
  • 2
    If you google "nodejs querystring" the first result is a link to the docs about the native querystring module... Commented Sep 12, 2013 at 16:35

1 Answer 1

8

You can use the native querystring module to parse query strings.

var http = require('http');
var qs = require('querystring');

http.createServer(function (req, res) {
  var str = req.url.split('?')[1];
  qs.parse(str);
});

Parsing query strings will return results in an object:

qs.parse('foo=bar&baz=qux&baz=quux&corge')
// returns
{ foo: 'bar', baz: ['qux', 'quux'], corge: '' }

You can also find the source of the module here.

Sign up to request clarification or add additional context in comments.

3 Comments

You will need to get pass only what is after the ?, more like qs.parse(req.url.split('?')[1])
Thanks! How would I then write an if function for when foo=bar in the querystring?
var result = qs.parse('foo=bar&baz=qux&baz=quux&corge'); if (result.foo == 'bar') {} is how you'd do that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.