JavaScript
A simple way to get data from servers or APIs and use it in your website—like asking the internet for information.
fetch()
What is fetch()?
fetch() is a way to request data from the web.
For example, you can use it to get a news article in JSON format from a server or to retrieve weather information from an API.
You can think of it as a delivery service: you provide a URL, and it brings the requested data back to your program.
Basic usage
This is the basic pattern:
JavaScript
fetch('https://example.com/data.json')
.then(response => response.json())
.then(data => {
console.log(data);
})
.catch(error => {
console.error('Error:', error);
});
Here is what happens:
fetch()requests the URL.- The server response is received as
response. - The response body is read with
.json()or another method. - The resulting value is used as
data.
Writing it with async/await
Using async/await often makes asynchronous code easier to read.
JavaScript
async function getData() {
try {
const response = await fetch('https://example.com/data.json');
const data = await response.json();
console.log(data);
} catch (error) {
console.error('Error:', error);
}
}
getData();
With await, the code follows a top-to-bottom flow while the asynchronous request is in progress.
What can fetch() do?
- GET
- Retrieve data. This is the default method.
- POST
- Send data.
- PUT / DELETE
- Update or delete data.
For example, this sends form-like data to a server:
JavaScript
fetch('https://example.com/send', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ name: 'Taro', message: 'Hello!' })
});
Common points to remember
- fetch() does not reject its Promise for an HTTP error such as 404. Check
response.okwhen you need to handle HTTP errors safely. - Requests to another origin may be restricted by CORS.
- Choose a response method that matches the data, such as
response.json()for JSON orresponse.text()for plain text.
Notes for intermediate users
fetch()returns a Promise, which makes asynchronous processing straightforward to compose.- Recent versions of Node.js also provide
fetchas a built-in API (Node.js 18 and later). - Use
AbortControllerwhen you need to cancel or time out a request.