fetch()
is a modern API in JavaScript used to make network requests, typically to fetch resources from a server. It returns a Promise that resolves to the Response object representing the response to the request.
The basic syntax for fetch()
is:
javascriptfetch(url)
.then(response => {
// handle response
})
.catch(error => {
// handle error
});
Here's what each part does:
fetch(url)
: Initiates a fetch request to the specified URL. This can be an absolute URL or a relative URL. This method returns a Promise that resolves to the Response object representing the response to the request..then(response => { ... })
: This is a method of the Promise returned byfetch()
. It takes a callback function that will be executed when the Promise is resolved (i.e., when the response is received). Theresponse
parameter contains the Response object representing the response to the request. Inside this callback, you handle the response, such as extracting data from it..catch(error => { ... })
: This is also a method of the Promise returned byfetch()
. It takes a callback function that will be executed if the Promise is rejected (i.e., if an error occurs during the fetch request). Theerror
parameter contains information about the error that occurred. Inside this callback, you handle the error, such as logging it or displaying an error message to the user.
Here's a simple example of using fetch()
to make a GET request to a URL and handle the response:
javascriptfetch('https://api.example.com/data')
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json(); // Parse the JSON content of the response
})
.then(data => {
console.log(data); // Do something with the parsed data
})
.catch(error => {
console.error('Fetch error:', error); // Log any errors that occur during the fetch
});
In this example, fetch()
makes a GET request to 'https://api.example.com/data'
. If the response is successful (i.e., if the status code is in the range 200-299), we parse the JSON content of the response using response.json()
in the first .then()
block. If there's an error during the fetch (e.g., network error or CORS issue), it's caught in the .catch()
block and logged to the console.
No comments:
Post a Comment