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>
This will result in a GET request to the following URL:
'http://myapi.com/orders?order_id=1'
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>
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!