📅  最后修改于: 2023-12-03 14:41:10.511000             🧑  作者: Mango
The Fetch API is an interface in JavaScript for fetching resources (e.g. data) asynchronously across the network (e.g. via HTTP).
fetch(url[, options])
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.log(error));
url
: The URL for the resource to be fetched.options
(optional): An object containing additional parameters for the request (e.g. headers, method, body).A Promise
that resolves to a Response
object.
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.log(error));
This example fetches data from "https://api.example.com/data", converts the response to JSON format, and logs the resulting object to the console.
The HTTP method (e.g. GET, POST) used for the request is specified using the method
option. By default, it is set to "GET".
fetch('https://api.example.com/data', {
method: 'POST',
body: JSON.stringify({ username: 'example', password: 'password'})
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.log(error));
This example sends a POST request to "https://api.example.com/data" with a JSON payload containing a username and password.
Custom headers can be included in the request using the headers
option.
fetch('https://api.example.com/data', {
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer myToken'
}
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.log(error));
This example includes custom headers "Content-Type" and "Authorization" with values "application/json" and "Bearer myToken" respectively.
The body
option is used to send data in the request body. It can be a FormData
, Blob
, ArrayBuffer
, or a JSON string.
fetch('https://api.example.com/data', {
method: 'POST',
body: JSON.stringify({ username: 'example', password: 'password'})
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.log(error));
This example sends a JSON payload containing a username and password in the request body.
Errors can be caught using the catch
method.
fetch('https://api.example.com/data')
.then(response => {
if (!response.ok) {
throw new Error(response.statusText);
}
return response.json();
})
.then(data => console.log(data))
.catch(error => console.log(error));
This example throws an error if the response status is not okay (e.g. 404 Not Found).