Open vikramlc opened 4 years ago
Sending POST requests:
function sendHttpRequest(method, url, data) {
const promise = new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
// xhr.open('GET', 'https://jsonplaceholder.typicode.com/posts');
xhr.open(method, url);
xhr.responseType = 'json';
xhr.onload = function() {
resolve(xhr.response);
// const listOfPosts = JSON.parse(xhr.response);
};
xhr.send(JSON.stringify(data));
});
return promise;
}
async function createPost(title, content) {
const userId = Math.random();
const post = {
title: title,
content: content,
userId: userId
};
sendHttpRequest('POST', 'https://jsonplaceholder.typicode.com/posts', post);
}
fetchPosts();
createPost('A dummy title', 'A dummy content');
Error handling with Http requests
// Error handling is triggered when there is an error from the API call.
xhr.onload = function() {
if (xhr.status >= 200 && xhr.status < 300) {
resolve(xhr.response);
} else {
reject(new Error('Something went wrong!!'));
}
// const listOfPosts = JSON.parse(xhr.response);
};
// This is triggered if there is any network error like timeout or no internet
xhr.onerror = function() {
reject(new Error('Failed to send request.'));
};
Http Requests with fetch() method
return fetch(url, {
method: 'POST',
body: JSON.stringify(data)
}).then(response => {
return response.json();
});
fetch() and error handling
return fetch(url, {
method: method,
body: JSON.stringify(data),
headers: {
'Content-Type': 'application/json'
}
})
.then(response => {
if (response.status >= 200 && response.status < 300) {
return response.json();
} else {
return response.json().then(errData => {
console.log(errData);
throw new Error('Something went wrong - server-side.');
});
}
})
.catch(error => {
console.log(error);
});
Note: We can send data to the API using the form data. We cannot send the json data directly using the form data. We need to send it through a object.
The advantage is we can send files easily with the form data.
Sending a GET request:
JSON data and parsing data: