easyhttp.js
// ES5 Object Oriented Library so we use prototypes instead of classes
//Create a constructor
function easyHTTP(){
this.http = new XMLHttpRequest();
}
// 4 different prototype method
// Make an HTTP GET Request
easyHTTP.prototype.get = function(url, callback){
this.http.open('GET', url, true);
let self = this;
self.http.onload = function(){
if(self.http.status === 200){
callback(null, self.http.responseText);
} else{
callback('Error' + self.http.status);
}
}
self.http.send();
}
// Make an HTTP POST Request
easyHTTP.prototype.post = function(url, data, callback ){
this.http.open('POST', url, true);
this.http.setRequestHeader('Content-type', 'application/json');
let self = this;
self.http.onload = function(){
callback(null, self.http.responseText);
}
this.http.send(JSON.stringify(data));
}
// Make an HTTP PUT Request
easyHTTP.prototype.put = function(url, data, callback ){
this.http.open('PUT', url, true);
this.http.setRequestHeader('Content-type', 'application/json');
let self = this;
self.http.onload = function(){
callback(null, self.http.responseText);
}
this.http.send(JSON.stringify(data));
}
// Make an HTTP DELETE Request
easyHTTP.prototype.delete = function(url, callback){
this.http.open('DELETE', url, true);
let self = this;
self.http.onload = function(){
if(self.http.status === 200){
callback(null, 'Post Deleted');
} else{
callback('Error' + self.http.status);
}
}
self.http.send();
}
app.js
// Instantiate
const http = new easyHTTP;
// Get Posts
http.get('https://jsonplaceholder.typicode.com/posts/',
function(err, posts){
if (err) {
console.log(err);
} else {
console.log(posts);
}
});
// Get Single Posts
http.get('https://jsonplaceholder.typicode.com/posts/1',
function(err, posts){
if (err) {
console.log(err);
} else {
console.log(posts);
}
});
// Create Data
const data = {
title : 'Custom Post',
body : 'This is a custom post'
};
/* // Create Post
http.post('https://jsonplaceholder.typicode.com/posts', data, function (err, post){
if (err) {
console.log(err);
} else {
console.log(post);
}
}); */
// Update Posts
http.put('https://jsonplaceholder.typicode.com/posts/5',
data, function (err, post){
if (err) {
console.log(err);
} else {
console.log(post);
}
});
// Delete Posts
http.delete('https://jsonplaceholder.typicode.com/posts/1',
function(err, response){
if (err) {
console.log(err);
} else {
console.log(response);
}
});
Leave a Reply