Home  >  Article  >  Web Front-end  >  How to Add Query Parameters to Fetch GET Requests in JavaScript?

How to Add Query Parameters to Fetch GET Requests in JavaScript?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-25 11:25:02200browse

How to Add Query Parameters to Fetch GET Requests in JavaScript?

Setting Query String in Fetch GET Requests

In the new Fetch API, a GET request with query parameters can be initiated by creating a URLSearchParams object, adding key-value pairs to it, and appending it to the request URL.

<code class="js">const params = new URLSearchParams({
  order_id: 1
});

const request = new Request({
  url: 'http://myapi.com/orders' + '?' + params.toString(),
  method: 'GET'
});

fetch(request);</code>

This will result in a GET request to the following URL:

'http://myapi.com/orders?order_id=1'

Example:

<code class="js">async function queryOrders() {
  const params = new URLSearchParams({
    // Example query parameter
    status: 'shipped'
  });

  const url = 'http://myapi.com/orders' + '?' + params.toString();

  const result = await (await fetch(url)).json();

  return result;
}</code>

The above is the detailed content of How to Add Query Parameters to Fetch GET Requests in JavaScript?. 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