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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With