Home  >  Article  >  Web Front-end  >  How to Add Query Strings to Fetch GET Requests?

How to Add Query Strings to Fetch GET Requests?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-25 21:27:03803browse

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);

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);

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!

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