Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fetch Api get params

I am trying to make a "GET" request using window.fetch, and I need to pass in a param which takes in an entire array as the value. For example, the request url should look like this

'https://someapi/production?moves=[]'

I have the following segment, which ends up in a 400 request, because the array gets evaluated to empty

let url = new URL('https://someapi/production');
let params = {moves: []};
Object.keys(params).forEach(key => url.searchParams.append(key, params[key]));
console.log(url);
fetch(url.href)
    .then(res => res.json())
    .then(val => {
          console.log(val);
     });

Upon inspecting the url.href looks like

https://someapi/production?moves=

where as I want it to be

https://someapi/production?moves=[]

Any suggestions on how I can achieve this?

like image 283
RRP Avatar asked Jul 16 '26 09:07

RRP


1 Answers

Because the second argument of url.searchParams.append(key, params[key]) is not a string, URLSearchParams.append will result in the value being stringified. I assume that's by calling the Array.prototype.toString() method on it, which omits the array brackets.

So, you'll either need to concatenate some brackets onto that string, or call a different method (like JSON.stringify mentioned in the comments) to keep the brackets.

like image 57
Andy Taton Avatar answered Jul 17 '26 21:07

Andy Taton