Making HTTP Requests with Fetch
The Fetch API provides a modern, promise-based way to make network requests.
fetch('https://api.example.com/data')
.then(response => {
if (!response.ok) throw new Error('Network response was not ok');
return response.json();
})
.then(data => {
console.log(data);
// update UI with data
})
.catch(error => console.error('Fetch error:', error));
POST Requests
Send data to a server using fetch with options.
fetch('https://api.example.com/submit', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: 'Alice', message: 'Hello' })
})
.then(res => res.json())
.then(result => console.log(result))
.catch(err => console.error(err));
AJAX with XMLHttpRequest
For legacy support, you can use XMLHttpRequest.
const xhr = new XMLHttpRequest();
xhr.open('GET', 'https://api.example.com/data');
xhr.onload = () => {
if (xhr.status === 200) {
const data = JSON.parse(xhr.responseText);
console.log(data);
}
};
xhr.send();