javascriptjqueryhttpfetch-api

Setting query string using Fetch GET request


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?


Solution

  • 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...