Got: Duplicate base searchParams with a URL with pre-existing querystring

Created on 25 Apr 2020  Â·  2Comments  Â·  Source: sindresorhus/got

Describe the bug

  • Node.js version: 14.0.0
  • OS & version: Ubuntu 18.04 (WSL)

    • got: 11.0.2

When using an extended got instance, with default searchParams and using a URL with a querystring, got will duplicate the default parameters and overwrite the URL's querystring.

Actual behaviour

See test code below, documentation says that passing in a searchParams option will overwrite the url's querystring but in this case got overwrites _and_ duplicates parameters.

Expected behaviour

According to [docs] got should delete the urls querystring and overwrite it with the searchParams option.

Code to reproduce

const got = require('got').extend({
  searchParams: new URLSearchParams({ foo: '123' }),
  // simple hook to print the final URL
  hooks: {
    beforeRequest: [
      ({ url }) => console.log('url %s', url)
    ]
  }
});

(async () => {
  await got('https://example.com?bar=456'); // https://example.com/?foo=123&foo=123
  await got(new URL('https://example.com?bar=456')); // https://example.com/?foo=123&foo=123

  await got('https://example.com', { searchParams: new URLSearchParams({ bar: '456' }) }); // https://example.com/?bar=456&foo=123
  await got(new URL('https://example.com'), { searchParams: new URLSearchParams({ bar: '456' }) }); // https://example.com/?bar=456&foo=123
})()

Checklist

  • [x] I have read the documentation.
  • [x] I have tried my code with the latest version of Node.js and Got.
bug regression ✭ help wanted ✭

All 2 comments

  await got('https://example.com', { searchParams: new URLSearchParams({ bar: '456' }) }); // https://example.com/?bar=456&foo=123
  await got(new URL('https://example.com'), { searchParams: new URLSearchParams({ bar: '456' }) }); // https://example.com/?bar=456&foo=123

The last two examples are perfectly valid. The first two indicate a bug.

Please note that in the first two you define options.searchParams through the defauts, so the URLs will be https://example.com/?foo=123 in both cases. To bypass this, simply pass searchParams as undefined precisely.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

sindresorhus picture sindresorhus  Â·  3Comments

quocnguyen picture quocnguyen  Â·  4Comments

alanzhaonys picture alanzhaonys  Â·  4Comments

erfanium picture erfanium  Â·  3Comments

carvallegro picture carvallegro  Â·  4Comments