1

I don't seem to be able to add parameters/queries to the URL. I'm trying to add parameters to the url. I'm trying to do it with .set() and .append() but neither seems to do what I thought it'd do. Am I misunderstanding what those methods are meant to do. The desired output should be:

http://newsapi.org/v2/top-headlines?country=gb&q=some_word

Code:

const url = new URL('/v2/top-headlines', 'http://newsapi.org')
const params = new URLSearchParams(url.search);
params.set('country', 'gb');
params.append('q', 'some_word')
console.log(url); // All good http://newsapi.org/v2/top-headlines
console.log(url.search); // empty object
console.log(params); // Empty string
mplungjan
  • 169,008
  • 28
  • 173
  • 236
Wasteland
  • 4,889
  • 14
  • 45
  • 91

2 Answers2

2

You meant to do this

const url = new URL('http://newsapi.org/v2/top-headlines');

url.searchParams.set('country', 'gb');
url.searchParams.set('q', 'some_word');
console.log(url);

// separately setting the searchParams 
/*
const url = new URL('/v2/top-headlines', 'http://newsapi.org'); // (relative,base)
const params = new URLSearchParams(url.search); // if the url had a queryString already
params.set('country', 'gb');
params.set('q', 'some_word');
url.search = params;
console.log(url);
*/
mplungjan
  • 169,008
  • 28
  • 173
  • 236
2

Try this

const url = new URL("/v2/top-headlines", "http://newsapi.org");

url.searchParams.append("country", "gb");
url.searchParams.append("q", "some word");

console.log(url.toString());

See

Mario
  • 4,784
  • 3
  • 34
  • 50