"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to add query string parameters to Fetch GET requests?

How to add query string parameters to Fetch GET requests?

Published on 2024-11-10
Browse:127

How to add query string parameters to Fetch GET requests?

Query String Addition in Fetch GET Requests

While exploring the Fetch API's query string capabilities, a developer aims to pass parameters to GET requests using a method akin to jQuery's $.ajax().

Solution

The new Fetch API employs URLSearchParams to tackle query string addition. This object offers a convenient way to build and modify query string parameters.

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

The URLSearchParams.toString() method encodes the parameter object into an appropriately formatted query string.

Alternatively, you can omit the .toString() call, as JavaScript automatically coerces non-string objects to strings when concatenated with strings. Note that this approach requires a deeper understanding of JavaScript.

Complete Example

Here's a comprehensive example with query parameters:

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();
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3