Created
November 14, 2020 07:32
-
-
Save whal-e3/0e436833d7169c21b7b3a063a382bf8e to your computer and use it in GitHub Desktop.
XHR http library example (GET, POST, PUT DELETE)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function easyHTTP() { | |
this.http = new XMLHttpRequest(); | |
} | |
// Make an HTTP GET Request | |
easyHTTP.prototype.get = function (url, callback) { | |
this.http.open('GET', url, true); | |
let self = this; | |
this.http.onload = function () { | |
if (self.http.status === 200) { | |
callback(null, self.http.responseText); | |
} else { | |
callback('Error: ' + self.http.status); | |
} | |
}; | |
this.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; | |
this.http.onload = function () { | |
callback(null, self.http.responseText); | |
}; | |
this.http.send(JSON.stringify(data)); | |
}; | |
// Make an HTTP PUT(update) Request | |
easyHTTP.prototype.put = function (url, data, callback) { | |
this.http.open('PUT', url, true); | |
this.http.setRequestHeader('Content-type', 'application/json'); | |
let self = this; | |
this.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; | |
this.http.onload = function () { | |
if (self.http.status === 200) { | |
callback(null, 'Post Deleted'); | |
} else { | |
callback('Error: ' + self.http.status); | |
} | |
}; | |
this.http.send(); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment