Query String Manipulation in GET Requests with Fetch API
In modern web development, the Fetch API offers a powerful mechanism for making HTTP requests. One common scenario involves sending GET requests with query strings. However, the semantics for adding query string parameters differ from the popular jQuery $.ajax() method.
Question:
How can a query string be added to a GET request using the Fetch API? For instance, consider the following URL:
http://myapi.com/orders?order_id=1
Answer:
The Fetch API provides two primary methods for appending query string parameters: URLSearchParams and URL.
Using URLSearchParams:
URLSearchParams allows for the manipulation of URL query strings. It offers an intuitive interface for adding, removing, and querying parameters. To construct a query string, create a URLSearchParams instance, add the desired parameters, and convert it to a string:
// Using URLSearchParams var request = new Request({ url: 'http://myapi.com/orders', method: 'GET' }); var params = new URLSearchParams(); params.append('order_id', 1); request.url += '?' + params.toString();
Using URL:
Alternatively, the URL class can be utilized to manipulate URLs directly. It provides methods for adding and retrieving parameters:
// Using URL var request = new Request({ url: new URL('http://myapi.com/orders'), method: 'GET' }); request.url.searchParams.append('order_id', 1);
In-Depth Example:
Consider the following scenario: fetching comments from a specific post on a RESTful API. Here's a complete example using the URLSearchParams approach:
// Fetch comments for a specific post using URLSearchParams async function fetchComments() { const postId = 1; const url = 'https://jsonplaceholder.typicode.com/comments?' + new URLSearchParams({ postId }).toString(); const response = await fetch(url); const comments = await response.json(); console.log(comments); } fetchComments();
By leveraging these techniques, developers can effectively add query strings to GET requests made with the Fetch API, enabling them to pass additional parameters to server-side endpoints and retrieve filtered results.
The above is the detailed content of How to Append Query String Parameters to GET Requests with Fetch API?. For more information, please follow other related articles on the PHP Chinese website!