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.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3