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

How to Add Query Strings to Fetch GET Requests?

Patricia Arquette
Release: 2024-10-25 21:27:03
Original
734 people have browsed it

How to Add Query Strings to Fetch GET Requests?

Query Strings with Fetch GET Request

The Fetch API provides a modern approach to making HTTP requests in JavaScript. By default, GET requests made using Fetch do not include query string parameters. To add a query string to a GET request, we can either use the URLSearchParams interface or concatenate the query string manually.

Using URLSearchParams:

The URLSearchParams interface allows us to easily create and manipulate query strings. To add a query string parameter, we can use the set() method:

const searchParams = new URLSearchParams();
searchParams.set('order_id', 1);

const request = new Request({
  url: 'http://myapi.com/orders',
  method: 'GET',
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded'
  },
  body: searchParams.toString()
});

fetch(request);
Copy after login

Concatenating the Query String:

Alternatively, we can concatenate the query string directly to the request URL:

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

fetch(request);
Copy after login

Note: If you choose to concatenate the query string manually, ensure that it is properly encoded to prevent invalid characters from breaking the request.

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