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!