Javascript 简明教程

JavaScript - Fetch API

What is a Fetch API?

JavaScript Fetch API 是一个 Web API,它允许 Web 浏览器向 Web 服务器发出 HTTP 请求。在 JavaScript 中,ES6 版本中引入了抓取 API。它是 XMLHttpRequest (XHR) 对象的替代方案,用于向服务器发出“GET”、“POST”、“PUT”或“DELETE”请求。

The JavaScript Fetch API is a web API that allows a web browser to make HTTP request to the web server. In JavaScript, the fetch API is introduced in the ES6 version. It is an alternative of the XMLHttpRequest (XHR) object, used to make a 'GET', 'POST', 'PUT', or 'DELETE' request to the server.

浏览器的窗口对象默认包含 Fetch API

The window object of the browser contains the Fetch API by default.

抓取 API 提供 fetch() 方法,该方法可用于跨网络异步访问资源。

The Fetch API provides fetch() method that can be used to access resources asynchronously across the web.

fetch() 方法允许您向服务器发出请求,并且它会返回一个承诺。之后,您需要解决承诺才能获得从服务器收到的响应。

The fetch() method allows you to make a request to the server, and it returns the promise. After that, you need to resolve the promise to get the response received from the server.

Syntax

您可遵循以下语法在 JavaScript 中使用 fetch() API -

You can follow the syntax below to use the fetch() API in JavaScript –

window.fetch(URL, [options]);
OR
fetch(URL, [options]);

Parameters

fetch() 方法接收两个参数。

The fetch() method takes two parameters.

  1. URL − It is an API endpoint where you need to make a request.

  2. [options] − It is an optional parameter. It is an object containing the method, headers, etc., as a key.

Return value

它返回您可使用“then…​catch”代码块或异步执行解决的承诺。

It returns the promise, which you can solve using the 'then…​catch' block or asynchronously.

Handling Fetch() API Response with 'then…​catch' Block

JavaScript fetch() API 返回承诺,并且您可使用“then…​catch”代码块处理它。

The JavaScript fetch() API returns the promise, and you can handle it using the 'then…​catch' block.

按照以下语法使用 fetch() API 和“then…​catch”代码块。

Follow the syntax below to use the fetch() API with the 'then…​catch' block.

fetch(URL)
.then(data => {
   // Handle data
})
.catch(err=> {
   // Handle error
})

在上述语法中,您可处理“then”代码块中的“data”以及“catch”代码块中的错误。

In the above syntax, you can handle the 'data' in the 'then' block and the error in the 'catch' block.

Example

在下面的代码中,我们使用 fetch() API 从给定 URL 中提取数据。它返回我们使用“then”代码块处理的承诺。

In the below code, we fetch the data from the given URL using the fetch() API. It returns the promise we handle using the 'then' block.

首先,我们将数据转换为 JSON 格式。然后,我们将数据转换为字符串并在网页上打印。

First, we convert the data into the JSON format. After that, we convert the data into the string and print it on the web page.

<html>
<body>
   <div id = "output"> </div>
   <script>
      const output = document.getElementById('output');
      const URL = 'https://jsonplaceholder.typicode.com/todos/5';
      fetch(URL)
	  .then(res => res.json())
	  .then(data => {
	     output.innerHTML += "The data from the API is: " + "<br>";
	  	 output.innerHTML += JSON.stringify(data);
   	  });
   </script>
</body>
</html>
The data from the API is:
{"userId":1,"id":5,"title":"laboriosam mollitia et enim quasi adipisci quia provident illum","completed":false}

Handling Fetch() API Response Asynchronously

您还可以使用 async/await 关键字异步解决 fetch() API 返回的承诺。

You can also solve the promise returned by the fetch() API asynchronously using the async/await keyword.

Syntax

用户可遵循以下语法将 async/await 关键字与 fetch() API 一起使用。

Users can follow the syntax below to use the async/await keywords with the fetch() API.

let data = await fetch(URL);
data = await data.json();

在上述语法中,我们使用“await”关键字来停止代码执行,直到承诺得到满足。然后,我们再次使用“await”关键字和 data.json() 停止函数执行,直到它将数据转换为 JSON 格式。

In the above syntax, we used the 'await' keyword to stop the code execution until the promise gets fulfilled. After that, we again used the 'await' keyword with the data.json() to stop the execution of the function until it converts the data into the JSON format.

Example

在下面的代码中,我们定义了 getData() 异步函数以使用 fetch() API 从给定 URL 中提取待办事项清单数据。然后,我们将数据转换为 JSON 并将输出打印到网页上。

In the code below, we have defined the getData()asynchronous function to fetch the to-do list data from the given URL using the fetch() API. After that, we convert the data into JSON and print the output on the web page.

<html>
<body>
<div id = "output"> </div>
<script>
   async function getData() {
      let output = document.getElementById('output');
      let URL = 'https://jsonplaceholder.typicode.com/todos/6';
      let data = await fetch(URL);
      data = await data.json();
      output.innerHTML += "The data from the API is: " + "<br>";
      output.innerHTML += JSON.stringify(data);
   }
   getData();
</script>
</body>
</html>
The data from the API is:
{"userId":1,"id":6,"title":"qui ullam ratione quibusdam voluptatem quia omnis","completed":false}

Options with Fetch() API

您还可以将对象作为第二个参数传递,其中包含作为键值对的选项。

You can also pass the object as a second parameter containing the options as a key-value pair.

Syntax

按照以下语法将选项传递给 Fetch() API。

Follow the syntax below to pass the options to the Fetch() API.

fetch(URL, {
    method: "GET",
    body: JSON.stringify(data),
    mode: "no-cors",
    cache: "no-cache",
    credentials: "same-origin",
    headers: {
        "Content-Type": "application/json",
    },
    redirect: "follow",
})

Options

此处,我们已提供了一些选项可传递给 fetch() API。

Here, we have given some options to pass to the fetch() API.

  1. method − It takes the 'GET', 'POST', 'PUT', and 'DELETE' methods as a value based on what kind of request you want to make.

  2. body − It is used to pass the data into the string format.

  3. mode − It takes the 'cors', 'no-cors', 'same-origin', etc. values for security reasons.

  4. cache − It takes the '*default', 'no-cache', 'reload', etc. values.

  5. credentials − It takes 'same-origin', 'omit', etc. values.

  6. headers − You can pass the headers with this attribute to the request.

  7. redirect − If you want users to redirect to the other web page after fulfilling the request, you can use the redirect attribute.

Example: Making a GET Request

在下面的代码中,我们已将“GET”方法作为选项传递给 fetch() API。

In the below code, we have passed the "GET" method as an option to the fetch() API.

Fetch() API 从给定的 API 端点获取数据。

Fetch () API fetches the data from the given API endpoint.

<html>
<body>
   <div id = "output"> </div>
   <script>
      let output = document.getElementById("output");
      let options = {
         method: 'GET',
      }
      let URL = "https://dummy.restapiexample.com/api/v1/employee/2";
      fetch(URL, options)
         .then(res => res.json())
         .then(res => {
            output.innerHTML += "The status of the response is - " + res.status + "<br>";
            output.innerHTML += "The message returned from the API is - " + res.message + "<br>";
            output.innerHTML += "The data returned from the API is - " + JSON.stringify(res.data);
         })
         .catch(err => {
            output.innerHTML += "The error returned from the API is - " + JSON.stringify(err);
         })
   </script>
</body>
</html>
The status of the response is - success
The message returned from the API is - Successfully! Record has been fetched.
The data returned from the API is - {"id":2,"employee_name":"Garrett Winters","employee_salary":170750,"employee_age":63,"profile_image":""}

Example (Making a POST Request)

在下面的代码中,我们创建了包含 emp_name 和 emp_age 属性的 employee 对象。

In the below code, we have created the employee object containing the emp_name and emp_age properties.

此外,我们还创建了包含方法、标头和正文属性的 options 对象。我们将“POST”用作方法的值,并将 employee 对象用作正文值(在将其转换为字符串后)。

Also, we have created the options object containing the method, headers, and body properties. We use the 'POST' as a value of the method and use the employee object after converting it into the string as a body value.

我们使用 fetch() API 向 API 端点发出 POST 请求以插入数据。发出 post 请求后,您可以在网页上看到响应。

We make a POST request to the API endpoint using the fetch() API to insert the data. After making the post request, you can see the response on the web page.

<html>
<body>
   <div id = "output"> </div>
   <script>
      let output = document.getElementById("output");
      let employee = {
         "emp_name": "Sachin",
         "emp_age": "30"
      }
      let options = {
         method: 'POST', // To make a post request
         headers: {
            'Content-Type': 'application/json;charset=utf-8'
         },
         body: JSON.stringify(employee)
      }
      let URL = "https://dummy.restapiexample.com/api/v1/create";
      fetch(URL, options)
         .then(res => res.json()) // Getting response
         .then(res => {
            output.innerHTML += "The status of the request is : " + res.status + "<br>";
            output.innerHTML += "The message returned from the API is : " + res.message + "<br>";
            output.innerHTML += "The data added is : " + JSON.stringify(res.data);
         })
         .catch(err => {
            output.innerHTML += "The error returned from the API is : " + JSON.stringify(err);
         })
   </script>
</body>
</html>
The status of the request is : success
The message returned from the API is : Successfully! Record has been added.
The data added is : {"emp_name":"Sachin","emp_age":"30","id":7425}

Example (Making a PUT Request)

在下面的代码中,我们创建了“animal”对象。

In the below code, we have created the 'animal' object.

此外,我们还创建了 options 对象。在 options 对象中,我们添加了“PUT”方法、标头和 animal 对象作为正文。

Also, we have created the options object. In the options object, we added the 'PUT' method, headers, and animal objects as a body.

然后,我们使用 fetch() API 在给定的 URL 中更新数据。您可以看到成功更新数据的输出响应。

After that, we use the fetch() API to update the data at the given URL. You can see the output response that updates the data successfully.

<html>
<body>
   <div id = "output"> </div>
   <script>
      let output = document.getElementById("output");
      let animal = {
         "name": "Lion",
         "color": "Yellow",
         "age": 10
      }
      let options = {
         method: 'PUT', // To Update the record
         headers: {
            'Content-Type': 'application/json;charset=utf-8'
         },
         body: JSON.stringify(animal)
      }
      let URL = "https://dummy.restapiexample.com/api/v1/update/3";
      fetch(URL, options)
         .then(res => res.json()) // Getting response
         .then(res => {
            console.log(res);
            output.innerHTML += "The status of the request is : " + res.status + "<br>";
            output.innerHTML += "The message returned from the API is : " + res.message + "<br>";
            output.innerHTML += "The data added is : " + JSON.stringify(res.data);
         })
         .catch(err => {
            output.innerHTML += "The error returned from the API is : " + JSON.stringify(err);
         })
   </script>
</body>
</html>
The status of the request is : success
The message returned from the API is : Successfully! Record has been updated.
The data added is : {"name":"Lion","color":"Yellow","age":10}

Example (Making a DELETE Request)

在下面的代码中,我们对给定的 URL 发出“DELETE”请求,以使用 fetch() API 删除特定数据。它返回包含成功消息的响应。

In the below code, we make a 'DELETE' request to the given URL to delete the particular data using the fetch() API. It returns the response with a success message.

<html>
<body>
   <div id = "output"> </div>
   <script>
      const output = document.getElementById("output");
      let options = {
         method: 'DELETE', // To Delete the record

      }
      let URL = " https://dummy.restapiexample.com/api/v1/delete/2";
      fetch(URL, options)
		 .then(res => res.json()) // After deleting data, getting response
		 .then(res => {
			output.innerHTML += "The status of the request is : " + res.status + "<br>";
			output.innerHTML += "The message returned from the API is : " + res.message + "<br>";
			output.innerHTML += "The data added is - " + JSON.stringify(res.data);
         })
		 .catch(err => {
		    output.innerHTML += "The error returned from the API is : " + JSON.stringify(err);
		 })
   </script>
</body>
</html>
The status of the request is : success
The message returned from the API is : Successfully! Record has been deleted
The data added is - "2"

Advantages of Using the Fetch() API

以下是使用 fetch() API 与第三方软件或 Web 服务器进行交互的一些好处。

Here are some benefits of using the fetch() API to interact with third-party software or web servers.

  1. Easy Syntax − It provides a straightforward syntax to make an API request to the servers.

  2. Promise-based − It returns the promise, which you can solve asynchronously using the 'then…​catch' block or 'async/await' keywords.

  3. JSON handling − It has built-in functionality to convert the string response data into JSON data.

  4. Options − You can pass multiple options to the request using the fetch() API.