📅  最后修改于: 2023-12-03 15:32:21.650000             🧑  作者: Mango
Fetch API is a modern interface for accessing and manipulating HTTP requests and responses in JavaScript. It is a part of the Web API specification and is supported in all major browsers like Google Chrome, Mozilla Firefox, Safari, and more.
The fetch API uses Promises, which allow us to handle the response asynchronously. Here is an example of how to use the fetch() method:
fetch('https://example.com/data')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error))
In the above example, we fetch data from the API endpoint https://example.com/data. The response is converted to JSON using the json() method and then logged to the console. Finally, we catch any errors that may occur during the request.
The fetch() method has several other options that can be used to customize the fetch request. Here are some examples:
fetch('https://example.com/data', {
headers: {
'Content-Type': 'application/json'
}
})
In the above example, we add a header to the request that specifies the content type as JSON.
fetch('https://example.com/data?param1=value1¶m2=value2')
Here, we add two query parameters, param1 and param2, with their respective values to the URL.
fetch('https://example.com/data', {
method: 'POST',
body: JSON.stringify({ data: 'example' }),
headers: {
'Content-Type': 'application/json'
}
})
In the above example, we make a POST request to the endpoint with JSON data included in the request body.
Fetch API provides an easy, modern way to make HTTP requests from JavaScript. With its asynchronous and customizable options, it allows developers to handle responses with ease and flexibility.