Basic GET Request
const xhr = new XMLHttpRequest();
xhr.open('GET', 'https://api.example.com/data', true);
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
console.log(xhr.responseText);
}
};
xhr.send();
Basic POST Request
const xhr = new XMLHttpRequest();
xhr.open('POST', 'https://api.example.com/data', true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
console.log(xhr.responseText);
}
};
xhr.send(JSON.stringify({ name: 'Alice', age: 25 }));
Basic GET Request
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
Basic POST Request
fetch('https://api.example.com/data', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ name: 'Alice', age: 25 }),
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
Using `Fetch`
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))
.catch(error => console.error('Error:', error));
With `XMLHttpRequest`
const xhr = new XMLHttpRequest();
xhr.open('GET', 'https://api.example.com/data', true);
xhr.onerror = function() {
console.error('Request failed');
};
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
console.log(xhr.responseText);
} else {
console.error('Error:', xhr.statusText);
}
}
};
xhr.send();
With `Fetch`
fetch('https://api.example.com/data')
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.catch(error => console.error('Fetch error:', error));
With `Fetch`
const params = new URLSearchParams({ userId: 1, postId: 2 });
fetch(`https://api.example.com/data?${params}`)
.then(response => response.json())
.then(data => console.log(data));
Basic Example
async function getData() {
try {
const response = await fetch('https://api.example.com/data');
if (!response.ok) throw new Error('Network response was not ok');
const data = await response.json();
console.log(data);
} catch (error) {
console.error('Error:', error);
}
}
getData();
With `Fetch`
fetch('https://api.example.com/data', {
method: 'GET',
headers: {
'Authorization': 'Bearer your_token',
'Content-Type': 'application/json'
}
})
.then(response => response.json())
.then(data => console.log(data));