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
?
A concise, modern approach:
fetch('https://example.com?' + new URLSearchParams({
foo: 'value',
bar: 2,
}).toString())
How it works: URLSearchParams toString() method will convert the URLSearchParams instance into a string representation, which happens to be a properly encoded query string.
It is also legal to leave out the .toString()
call like so: fetch('https://...' + new URLSearchParams(...))
. JavaScript automatically calls .toString()
when an object is concatenated with a string. This does require future code readers to have a deeper understanding of the language to understand your code.
A complete example of a fetch request with query parameters:
// Real example you can copy-paste and play with.
// jsonplaceholder.typicode.com provides a dummy rest-api
// for this sort of purpose.
async function doAsyncTask() {
const url = (
'https://jsonplaceholder.typicode.com/comments?' +
new URLSearchParams({ postId: 1 }).toString()
);
const result = await fetch(url)
.then(response => response.json());
console.log('Fetched from: ' + url);
console.log(result);
}
doAsyncTask();
If you are using/supporting...
IE: Internet Explorer does not provide native support for URLSearchParams or fetch, but there are polyfills available.
Node: As of Node 18 there is native support for the fetch API (in version 17.5 it was behind the --experimental-fetch
flag). In older versions, you can add the fetch API through a package like node-fetch. URLSearchParams comes with Node, and can be found as a global object since version 10. In older version you can find it at require('url').URLSearchParams
.
TypeScript: The values provided to URLSearchParams
will be auto-coerced into a string, which is why TypeScript's definition for URLSearchParams
requires you to provide all values as strings. Those who don't use TypeScript may be comfortable providing other value types to this function if they feel the coercion behavior is intuitive. For examples, numbers will behave exactly as you would expect, while the way arrays get implicitly coerced may cause confusion to future readers.
TypeScript v4 or older with Node: Older versions of TypeScript did not offer type definitions for the global URLSearchParams in the Node environment. The simplest workaround is to just import it from the url
module. This later got resolved at some point during v4 (I'm not sure what the exact version is that fixes this). See this issue for more info.