Home > Web Front-end > JS Tutorial > body text

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

Patricia Arquette
Release: 2024-10-25 11:25:02
Original
199 people have browsed it

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>
Copy after login

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

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

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!