4 ways to call api - XMLHttpRequest, fetch, axios and jquery
XMLHttpRequest
console.log(window.XMLHttpRequest); // Built in method
// Event - onload(), onerror()
// Property - response, responseText, responseType, responseURL, status, statusText open(), send(), setRquestHeader()
// Function - open(), send(), setRequestHeader(),
// Primary Setup
const getData = () => {
const xhr = new XMLHttpRequest(); // Instant Create Object
xhr.open('GET', 'https://jsonplaceholder.typicode.com/posts'); // Request Open
xhr.onload = () => {
// Request Handle
let data = xhr.response;
console.log(JSON.parse(data)); // convert JSON to JS
};
xhr.onerror = () => {
// Request Handle
console.log('error is here');
};
xhr.send(); // Request Send
};
getData();
///////////////////////////////////////////
// Final Setup All Methods
const makeRequest = (method, url, data) => {
const xhr = new XMLHttpRequest();
xhr.open(method, url); // true = Asynchronous, false = Synchronous
xhr.setRequestHeader('Content-type', 'application/json'); // Between open and send
xhr.onload = () => {
let data = xhr.response;
console.log(JSON.parse(data)); // JSON to JavaScript
// Checking other properties
console.log(xhr.responseText);
console.log(xhr.responseType); // Blank
console.log(xhr.responseURL);
console.log(xhr.status);
console.log(xhr.statusText); // Blank
};
xhr.onerror = () => {
console.log('error is here');
};
xhr.send(JSON.stringify(data)); // JavaScript to JSON
};
// Get Data - GET
const getData = () => {
makeRequest('GET', 'https://jsonplaceholder.typicode.com/posts');
};
// Send Data - POST
const sendData = () => {
makeRequest('POST', 'https://jsonplaceholder.typicode.com/posts', {
title: 'foo',
body: 'bar',
userId: 1,
});
};
// Update Data - PUT
const updateData = () => {
makeRequest('PUT', 'https://jsonplaceholder.typicode.com/posts/1', {
// Change (post/[ID])
id: 1, // Important
title: 'fooooo',
body: 'barrrr',
userId: 1,
});
};
// Update Single Data - PATCH
const updateSingleData = () => {
makeRequest('PATCH', 'https://jsonplaceholder.typicode.com/posts/1', {
// Change (post/[ID])
title: 'This is changed',
});
};
// Delete Data - DELETE
const deleteData = () => {
makeRequest('DELETE', 'https://jsonplaceholder.typicode.com/posts/1'); // Change (post/[ID])
};
getData();
sendData();
updateData();
updateSingleData();
deleteData();
fetch
👉🏻 fetch() has replaced XMLHttpRequest
👉🏻 fetch() - global method for making HTTP Request
👉🏻 2 ways to call - then, async/await
👉🏻 fetch() is easy to use compare to XMLHttpRequest
👉🏻 fetch() returns a promise
👉🏻 Returned promise can only handle network error
👉🏻 Does not support all the older browser
// Getting a resource
fetch('https://jsonplaceholder.typicode.com/posts/1')
.then((res) => res.json()) // ReadableStream to json
.then((res) => console.log(res))
.catch((err) => console.log(err));
// Error Handling
fetch('https://jsonplaceholder.typicode.com/posts/1')
.then((res) => {
if (!res.ok) {
const message = `Error: ${res.status}`;
throw new Error(message);
}
return res.json();
})
.then((res) => console.log(res))
.catch((err) => console.log(err));
// Creating a resource
fetch('https://jsonplaceholder.typicode.com/posts', {
method: 'POST',
body: JSON.stringify({
title: 'foo',
body: 'bar',
userID: 1,
}),
headers: {
'Content-type': 'application/json; charset=UTF-8',
},
})
.then((res) => {
if (!res.ok) {
const message = `Error: ${res.status}`;
throw new Error(message);
}
return res.json();
})
.then((res) => console.log(res))
.catch((err) => console.log(err));
// Async/Await
const makeRequest = async (url, config ) => {
const res = await fetch(url, config);
if (!res.ok) {
const message = `Error: ${res.status}`;
throw new Error(message);
}
const data = await res.json();
return data;
};
// Get Data
const getData = () => {
makeRequest('https://jsonplaceholder.typicode.com/posts')
.then((res) => console.log(res))
.catch((err) => console.log(err));
};
// Send Data
const sendData = () => {
makeRequest('https://jsonplaceholder.typicode.com/posts', {
method: 'POST',
body: JSON.stringify({
title: 'foo',
body: 'bar',
userID: 1,
}),
headers: {
'Content-type': 'application/json; charset=UTF-8',
},
})
.then((res) => console.log(res))
.catch((err) => console.log(err));
};
Axios
👉🏻 Axios is a js library, Not by default or built in
👉🏻 It helps to make requests from browser (plain js/Vue/React/Angular), node.js
👉🏻 Very easy to use
👉🏻 It supports all modern browser including IE because It's based on XMLHttpRequest
👉🏻 It returns promise
👉🏻 Throws error brilliantly
👉🏻 No need to set header cause axios is intelligent
👉🏻 Axios returns response objects - data, status, statusText, headers, config
// axios(config)
// axios(url [, config])
// axios.get(url [, config])
// axios.post(url [, config])
// axios.put(url [, config])
// axios.patch(url [, config])
// axios.delete(url [, config])
const makeRequest = async (config) => {
return await axios(config);
};
const getData = () => {
makeRequest('https://jsonplaceholder.typicode.com/posts')
.then((res) => console.log(res))
.catch((err) => console.log(err));
};
getData();
const createData = () => {
makeRequest({
url: 'https://jsonplaceholder.typicode.com/posts',
method: 'post',
data: JSON.stringify({
title: 'foo',
body: 'bar',
userId: 1,
}),
})
.then((res) => console.log(res))
.catch((err) => console.log(err));
};
createData();
const updateData = () => {
makeRequest({
url: 'https://jsonplaceholder.typicode.com/posts/1',
method: 'put',
data: JSON.stringify({
id: 1,
title: 'fooma',
body: 'barma',
userId: 1,
}),
})
.then((res) => console.log(res.data))
.catch((err) => console.log(err));
};
updateData();
const deleteData = () => {
makeRequest({
url: 'https://jsonplaceholder.typicode.com/posts/1',
method: 'delete',
})
.then((res) => console.log(res.data))
.catch((err) => console.log(err));
};
deleteData();
0 Comments