The spec does not document any way to specify GET query parameters (e.g. search?q=unicorns&limit=10&foobar) for a request. GET is the most common case but in practice, query parameters may be used with any HTTP method.
As I understand, the way to do this is using URLSearchParams from the URL spec. It would be good to provide a clearer view of how these two APIs fit together, especially as query strings are often supported directly by the high-level XHR APIs that fetch is meant to replace (e.g. jQuery.ajax or reqwest), often as a data option for example.
In general, it feels like it would be really great to have a boilerplate-free way to use only native web APIs to do such common things as passing URI parameters.
See also this Twitter thread.
Edit: see https://fetch.spec.whatwg.org/#fetch-api for a working example.
Example could be something like:
var url = new URL("https://example.org/api"),
params = { first: "x", second: "y" }
Object.keys(params).forEach((key, value) => { url.searchParams.append(key, value) })
fetch(url).then(/* ... */)
URL objects don't seem to have a .searchParams property, at least not in Chrome 48.
That's a Chrome bug, not really relevant to the spec.
For better or worse, this page is the first result when you google "whatwg fetch url params". Just trying to save future googlers some potentially wasted time.
@annevk, the URL objects do not have that .searchParams property. These are the fixes it requires:
function urlWithParams(urlString, params={}) {
var url = new URL(urlString);
var searchParams = new URLSearchParams();
Object.keys(params).forEach((key) => {
searchParams.append(key, params[key]);
});
url.search = searchParams.toString();
return url.toString();
}
Object.keys will return an array and the values will be lost in the foreach callback. I leave this function that maybe useful for those who want to add params to a url
See the last three comments prior to yours.
I just wanted to leave here a working example ...
Ah, that makes sense! Hopefully Chrome fixed their bug soon...
Agreed :)
@kopz9999 has worked in Firefox for ages. \o/
@annevk, I agree on the part of searchParams in Firefox, but this part is wrong:
Object.keys(params).forEach((key, value) => { url.searchParams.append(key, value) })
This part will always put the index as a value: "https://example.org/api?first=0&second=1"
I just wanted to leave a working example since this page is one of the first results thrown by google
Ah I see, updated my comment to point to the standard where that is fixed.
Yes, I think that is already fixed on this repo: https://github.com/whatwg/fetch
But google brings this page :P
superagent is much simpler, \o/
Most helpful comment
For better or worse, this page is the first result when you google "whatwg fetch url params". Just trying to save future googlers some potentially wasted time.