📅  最后修改于: 2023-12-03 15:01:37.512000             🧑  作者: Mango
Fetch is a modern web API that provides a simple interface to fetch and manipulate resources across the network. The Fetch API is a low-level interface which enables fetching resources asynchronously via HTTP or other network protocols.
The fetch() method is used to make asynchronous requests to the server and receives an HTTP response. It can be used to request files, APIs, or any other resources that are accessible over the network.
fetch(url, options)
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error))
url
: A string representing the URL of the resource you want to fetch.options
: An object containing request options like method, headers, body, cache, and mode. These options are optional, but they allow you to customize the request.The fetch() method returns a Promise that resolves to the Response of the request. This Response object represents the response to the request made.
fetch('https://jsonplaceholder.typicode.com/todos/1')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error))
In this example, we are fetching a JSON data from an API using the fetch() method. We are converting the response to JSON data using the .json() method. Finally, we are logging the data to the console.
fetch('https://jsonplaceholder.typicode.com/posts', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
title: 'foo',
body: 'bar',
userId: 1
})
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error))
In this example, we are sending a POST request to an API endpoint. We are setting the request method to POST and providing the request body as a JSON string using the JSON.stringify() method. We are also setting the Content-Type header to application/json. Finally, we are logging the response to the console.
The fetch() method is a powerful feature of modern web development that enables developers to make asynchronous requests to the server and handle responses more efficiently. It supports a wide range of request options and is easy to use. Check out MDN web docs for more information on using the fetch() method.