JS - URLSearchParams - 添加参数

JS - URLSearchParams - add parameters

我似乎无法将 parameters/queries 添加到 URL。我正在尝试向 url 添加参数。我正在尝试使用 .set() 和 .append() 来做这件事,但似乎都没有按照我的想法去做。我是否误解了这些方法的用途。所需的输出应为:

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

代码:

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

你是故意的

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

试试这个

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