Node: http.get method() ignores query params when passing an URL as first argument

Created on 6 Aug 2018  路  7Comments  路  Source: nodejs/node

  • Version: v8.10.0
  • Platform: Linux 4.15.0-29-generic Ubuntu SMP Tue Jul 17 15:39:52 UTC 2018 x86_64 x86_64 x86_64 GNU/Linux
  • Subsystem: http

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
}));

doc http question url whatwg-url

All 7 comments

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:

  • Remove require('url')
  • Change URL.parse to new URL
  • Change url.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.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

danielstaleiny picture danielstaleiny  路  3Comments

cong88 picture cong88  路  3Comments

Icemic picture Icemic  路  3Comments

fanjunzhi picture fanjunzhi  路  3Comments

akdor1154 picture akdor1154  路  3Comments