AJAX Requests in JavaScript | CheatSheet
GET Request
fetch('url', {
headers: { 'Content-Type': 'application/json' }
})
.then(response => response.text())
.then(data => {
console.log(data);
})
.catch(error => {
console.error(error);
});
POST Request
fetch('url', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ key: 'value' })
})
.then(response => response.text())
.then(data => {
console.log(data);
})
.catch(error => {
console.error(error);
});
PUT Request
fetch('url', {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ key: 'value' })
})
.then(response => response.text())
.then(data => {
console.log(data);
})
.catch(error => {
console.error(error);
});
DELETE Request
fetch('url', {
method: 'DELETE',
headers: { 'Content-Type': 'application/json' }
})
.then(response => response.text())
.then(data => {
console.log(data);
})
.catch(error => {
console.error(error);
});
Handling Custom Headers
fetch('url', {
headers: { 'Authorization': 'Bearer token' }
})
.then(response => response.text())
.then(data => {
console.log(data);
})
.catch(error => {
console.error(error);
});