I'm trying to use the new Fetch API:
I am making a GET
request like this:
var request = new Request({
url: 'http://myapi.com/orders',
method: 'GET'
});
fetch(request);
However, I'm unsure how to add a query string to the GET
request. Ideally, I want to be able to make a GET
request to a URL
like:
'http://myapi.com/orders?order_id=1'
In jQuery
I could do this by passing {order_id: 1}
as the data
parameter of $.ajax()
. Is there an equivalent way to do that with the new Fetch API
?
Update March 2017:
URL.searchParams support has officially landed in Chrome 51, but other browsers still require a polyfill.
The official way to work with query parameters is just to add them onto the URL. From the spec, this is an example:
var url = new URL("https://geo.example.org/api"),
params = {lat:35.696233, long:139.570431}
Object.keys(params).forEach(key => url.searchParams.append(key, params[key]))
fetch(url).then(/* … */)
However, I'm not sure Chrome supports the searchParams
property of a URL (at the time of writing) so you might want to either use a third party library or roll-your-own solution.
Update April 2018:
With the use of URLSearchParams constructor you could assign a 2D array or a object and just assign that to the url.search
instead of looping over all keys and append them
var url = new URL('https://sl.se')
var params = {lat:35.696233, long:139.570431} // or:
var params = [['lat', '35.696233'], ['long', '139.570431']]
url.search = new URLSearchParams(params).toString();
fetch(url)
Sidenote: URLSearchParams
is also available in NodeJS
const { URL, URLSearchParams } = require('url');
There's also developer.mozilla.org/en-US/docs/Web/API/URLSearchParams/…, tho as of this writing it's still making its way through spec, and not well-supported yet. And the API is more like Java than JS. :/
See caniuse.com/#feat=urlsearchparams for support for the
URLSearchParams
interface; I would assume (though I'm not 100% certain) that the browsers in red there are exactly the browsers for whichURL
objects will not have the.searchParams
property. Importantly, Edge still does not have support.From the documentation: "Note that using a URLSearchParams instance is deprecated; soon browsers will just use a USVString for the init." source: developer.mozilla.org/en-US/docs/Web/API/URLSearchParams/…
new URLSearchParams
doesn't seem to work correctly withArray
properties. I expected it to convert the propertyarray: [1, 2]
toarray[]=1&array[]=2
, but converted it toarray=1,2
. Manually using theappend
method of it does result inarray=1&array=2
, but I would have to iterate over params object, and do that only for array types, not very ergonomic.It was indeed added in error :) github.com/mdn/sprints/issues/2856