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

4
  • 2
    console.log(params.toString()) - the variable params contains an object, not a string. Commented Jun 27, 2020 at 19:25
  • I think you are not assigning any values to url.search Commented Jun 27, 2020 at 19:27
  • @VLAZ That worked but how would I update the url object? Commented Jun 27, 2020 at 19:28
  • 1
    url.search = params.toString() Commented Jun 27, 2020 at 19:29

2 Answers 2

3

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);
*/

Sign up to request clarification or add additional context in comments.

Comments

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

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.