Home  >  Article  >  Web Front-end  >  How can I append query strings to my GET requests using the Fetch API?

How can I append query strings to my GET requests using the Fetch API?

Linda Hamilton
Linda HamiltonOriginal
2024-10-26 03:21:27838browse

How can I append query strings to my GET requests using the Fetch API?

Query String Manipulation with the Fetch API

In pursuit of creating GET requests with custom query parameters using the Fetch API, a pertinent question arises: "How can I append query strings to my requests?" Originating from the imperative need to tailor GET requests like 'http://myapi.com/orders?order_id=1', the query remains - is there an equivalent to jQuery's {order_id: 1} data parameter within Fetch?

A Modern, Concise Resolution

Unlocking the potential of URLSearchParams, a contemporary solution emerges. Employing its toString() method, one can effortlessly transform the instance into an encoded query string, seamlessly appending it to the request URL:

<code class="javascript">fetch('https://example.com?' + new URLSearchParams({
  foo: 'value',
  bar: 2,
}).toString())</code>

URLSearchParams meticulously converts the object into the desired query string format, eliminating the need for manual encoding. Alternatively, one can omit the toString() call, leveraging JavaScript's automatic conversion upon string concatenation. However, this approach necessitates a deeper understanding of JavaScript's inner workings.

Comprehensive Fetch Example

For a complete illustration, consider the following example, which performs a fetch request with customized query parameters:

<code class="javascript">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();</code>

Unleashing Query String Parameters

With these techniques at your disposal, you now possess the ability to effortlessly append query strings to your GET requests using the Fetch API, empowering you to shape your data retrieval operations with precision and efficiency.

The above is the detailed content of How can I append query strings to my GET requests using the Fetch API?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn