JavaScript Fetch API
What is the Fetch API in JavaScript?
The Fetch API is a modern interface that allows you to make network requests similar to XMLHttpRequest. It provides a more powerful and flexible feature set for handling HTTP requests and responses in a promise-based manner.
How do you make a simple GET request using the Fetch API?
You can make a GET request by calling the fetch() function with the URL of the resource you want to retrieve.
fetch('https://api.example.com/data')
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json(); // Parse JSON data
})
.then(data => {
console.log(data); // Handle the data
})
.catch(error => {
console.error('Error fetching data:', error);
});
How do you make a POST request using the Fetch API?
To make a POST request, you need to specify the method and body in the options object passed to fetch().
const data = { name: 'Alice', age: 30 };
fetch('https://api.example.com/users', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data) // Convert data to JSON string
})
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json(); // Parse JSON response
})
.then(data => {
console.log('User created:', data);
})
.catch(error => {
console.error('Error:', error);
});
What does the response.ok property do?
The response.ok property is a boolean indicating whether the HTTP response status is in the successful range (200–299). It helps determine if the request was successful before processing the response.
fetch('https://api.example.com/data')
.then(response => {
if (!response.ok) {
throw new Error('Failed to fetch data');
}
return response.json();
})
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
How do you handle errors in the Fetch API?
Errors can be handled by using the catch() method at the end of the promise chain. Additionally, you can check for response status using response.ok to handle HTTP errors specifically.
fetch('https://api.example.com/data')
.then(response => {
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return response.json();
})
.then(data => console.log(data))
.catch(error => {
console.error('Error fetching data:', error.message);
});
Can you use the Fetch API to handle form submissions?
Yes, you can use the Fetch API to submit forms by capturing the form data and sending it as a POST request.
const form = document.getElementById('myForm');
form.addEventListener('submit', (event) => {
event.preventDefault(); // Prevent default form submission
const formData = new FormData(form);
fetch('https://api.example.com/submit', {
method: 'POST',
body: formData // Sending form data
})
.then(response => response.json())
.then(data => console.log('Form submitted:', data))
.catch(error => console.error('Error:', error));
});
What is the difference between the Fetch API and XMLHttpRequest?
The Fetch API offers a more powerful and flexible feature set than XMLHttpRequest. Key differences include:
- Promise-based: Fetch uses promises, making it easier to work with asynchronous operations.
- Better handling of responses: Fetch provides a simpler interface for handling responses, including streaming support.
- More modern API: Fetch supports modern features like CORS, and can easily handle JSON, text, and other response types.
How do you send custom headers with the Fetch API?
You can send custom headers by including a headers object in the options of the fetch request.
fetch('https://api.example.com/data', {
method: 'GET',
headers: {
'Authorization': 'Bearer your-token',
'Custom-Header': 'CustomValue'
}
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
What is the difference between fetch() and axios?
Both fetch() and axios are used for making HTTP requests, but they have some differences:
- Promise-based: Both are promise-based, but axios is built on top of fetch and includes additional features.
- Automatic JSON transformation: Axios automatically transforms response data into JSON, while fetch requires manual parsing.
- Interceptors: Axios allows for request and response interceptors, enabling modification of requests and responses before they are handled.
- Support for older browsers: Axios supports older browsers like Internet Explorer, while fetch may require polyfills.