0

I am conducting an exercise using nodejs in the REPL, I have been given a URL and am required to use querystring.parse() on it after accessing it via process.argv[] to retrieve the value of a and b and log them to the console. This is the string:

"http://127.0.0.1:8080/test?a=100&b=200"

Here is my code so far

 const qs = require("querystring");   
        function fn() {
            var query = qs.parse(process.argv[2]);
            console.log("query a is " + query["a"]);
            console.log("query b is " + query["b"]);
        }
        module.exports.fn = fn();

The exercise requires the final two console logs to return as follows:

     'query a is 100'
     'query b is 200'

But the output I am getting is:

      query a is undefined
      query b is 200

and when I return the query object itself I get this:

         { 'http://127.0.0.1:8080/test?a': '100', b: '200' }

3 Answers 3

1

i believe you need the 'url' module to parsed the full url, because the 'querystring' module itself will only correctly parse the query string.

const url = require("url")
const qs = require("querystring");   
    function fn() {
        const parsedUrl = url.parse(process.argv[2])
        const query = qs.parse(parsedUrl.query);
        console.log("query a is " + query["a"]);
        console.log("query b is " + query["b"]);
    }
    module.exports.fn = fn();
Sign up to request clarification or add additional context in comments.

Comments

1

qs parses query strings rather than URLs.

Try using URL Parser.

(new URL(addr).search.substring(1))

qs.parse("title=querystring&action=edit") 

For getting params passed, call

new URL(addr).searchParams 

1 Comment

I would but I need to submit something using both the URL and querystring modules nodejs
0

Beacuse querystring parses the query only so tis will give you both the queries as parsed by the module

const qs = require("querystring");   
        function fn() {
            var query = qs.parse(process.argv[2]);
            console.log("query a is " + query["http://127.0.0.1:8080/test?a"]);
            console.log("query b is " + query["b"]);
        }
        module.exports.fn = fn();

else you can use url module

var url = require('url');
var url_parts = url.parse('http://127.0.0.1:8080/test?a=100&b=200', true);
var query = url_parts.query;
console.log(query)

Comments

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.