Setting query string using Fetch GET request Setting query string using Fetch GET request javascript javascript

Setting query string using Fetch GET request


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');


A concise, modern approach:

fetch('https://example.com?' + new URLSearchParams({    foo: 'value',    bar: 2,}))

URLSearchParams's toString() function will convert the query args into a string that can be appended onto the URL. In this example, toString() is called implicitly when it gets concatenated with the URL. You may wish to explicitly call toString() to show your intentions.


IE does not support URLSearchParams (or fetch), but there are polyfills available.

If using node, 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.

If you're using node and typescript together, you'll find that, due to some technical limitations, typescript does not offer type definitions for the global URLSearchParams. The simplist workaround is to just import it from the URL module. See here for more info.


let params = {  "param1": "value1",  "param2": "value2"};let query = Object.keys(params)             .map(k => encodeURIComponent(k) + '=' + encodeURIComponent(params[k]))             .join('&');let url = 'https://example.com/search?' + query;fetch(url)  .then(data => data.text())  .then((text) => {    console.log('request succeeded with JSON response', text)  }).catch(function (error) {    console.log('request failed', error)  });