-
Notifications
You must be signed in to change notification settings - Fork 329
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Document usage for GET requests with URI parameters #56
Comments
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(/* ... */) |
|
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 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 Object.keys(params).forEach((key, value) => { url.searchParams.append(key, value) }) This part will always put the index as a value: |
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 |
superagent is much simpler, \o/ |
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 thatfetch
is meant to replace (e.g. jQuery.ajax or reqwest), often as adata
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.
The text was updated successfully, but these errors were encountered: