When passing an URL with query params as the first argument to http.get() method, the query is ignored.
const URL = require('url');
const http = require('http');
const assert = require('assert');
function parseJsonResp(next) {
return function(resp) {
var raw = '';
resp.on('data', function(chunk) {
raw += chunk;
});
resp.on('end', function() {
next(null, JSON.parse(raw));
});
}
};
const url = URL.parse('http://httpbin.org/get');
url.query = {foo: 'bar'}
http.get(url, parseJsonResp(function(err, obj) {
assert(obj.args.foo === 'bar'); // It fails here
}));
http.get doesn't expect a whatwg url object, it expects an options argument similar to the output of url.parse()
The documentation says that the first argument can be an Object, a string or an URL.
It is a very subtle thing... the documentation says URL, and what you passed was a Url. Click on the links to see the difference.
Try the following:
const http = require('http');
const assert = require('assert');
function parseJsonResp(next) {
return function(resp) {
var raw = '';
resp.on('data', function(chunk) {
raw += chunk;
});
resp.on('end', function() {
next(null, JSON.parse(raw));
});
}
};
const url = new URL('http://httpbin.org/get');
url.searchParams.set('foo', 'bar')
http.get(url, parseJsonResp(function(err, obj) {
assert(obj.args.foo === 'bar'); // It fails here
}));
Key changes:
require('url')URL.parse to new URLurl.query = to url.searchParams.set()OK. Thanks! :+1:. Shouldn't this be explicit on documentation?
@gabriel-araujjo just to be clear, this issue can be closed now? Ah, missed your edit. Suggestions on how to make it more clear?
I guess an example with that distinction is enough.
The http URL has since been updated to support URL objects and properly handles the query string now so this can be closed.