The fetch API is a JavaScript function that allows devs to make HTTP requests. You can fetch (or retrieve) data, submit data, update existing data, and more. And all of this comes in a more powerful, flexible, and cleaner package than XMLHttpRequest
.
When making these requests, we primarily deal with four types of HTTP methods, although there are several more:
- GET: For retrieving data from the server. It doesn't change the server state.
- POST: For sending data to the server, typically resulting in a change on the server.
- PUT: For replacing a current resource with a new one.
- DELETE: For removing a specified resource.
Note that the code samples below use async/await
for simplicity. If you don't want to use async/await
, you can change these examples to use the .then()
pattern.
For a GET request, try this:
async function getData() {
try {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
console.log(data);
} catch (error) {
console.log('Error:', error);
}
}
getData();
In this block, we're retrieving data and making it available under the variable data
.
For POSTing JSON data, use this:
async function postData() {
try {
const response = await fetch('https://api.example.com/data', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({key: 'value'})
});
const data = await response.json();
console.log(data);
} catch (error) {
console.log('Error:', error);
}
}
postData();
This block POSTs JSON data to a resource. You can capture the response JSON as data
.