乐闻世界logo
搜索文章和话题

Setting query string using Fetch GET request

1个答案

1

When using the Fetch API for GET requests, the query string is appended to the URL, starting with a question mark (?), and parameters are separated by ampersands (&). Below is an example of the steps to send a GET request using the Fetch API and set the query string:

Suppose we need to retrieve user data from an API, with the basic URL being https://api.example.com/users, and we want to filter this user data based on age and nationality.

Step 1: Constructing the URL and Query String

First, we need to construct a URL that includes query parameters. Suppose we want to query users who are 30 years old and from the USA; we can write it as:

javascript
const baseUrl = 'https://api.example.com/users'; const queryParams = new URLSearchParams({ age: 30, nationality: 'USA' }); const url = `${baseUrl}?${queryParams.toString()}`;

Here, the URLSearchParams object is used to conveniently construct the query string. By calling the toString() method, it automatically converts the parameter object into a format suitable for URLs.

Step 2: Sending the GET Request with Fetch

Now that the URL includes the necessary query parameters, we can use the Fetch API to send the GET request:

javascript
fetch(url) .then(response => { if (!response.ok) { throw new Error('Network response was not ok'); } return response.json(); }) .then(data => { console.log('Data retrieved:', data); }) .catch(error => { console.error('Error fetching data:', error); });

In this code snippet, fetch(url) initiates a network request to the specified URL with the query string. The .then(...) chain processes the response: first checking if the response is successful, then parsing the JSON content, and finally logging or handling errors in the console.

Summary

By using this approach, you can flexibly send GET requests with query parameters via the Fetch API to retrieve or filter the data you need. This method is particularly useful when working with RESTful APIs, as it allows you to dynamically construct query strings based on your requirements.

2024年7月12日 14:15 回复

你的答案