First commit

This commit is contained in:
Dita Aji Pratama 2023-12-27 23:55:31 +07:00
parent 38b6dbe860
commit a6bea55189
2 changed files with 71 additions and 1 deletions

View File

@ -1 +1,38 @@
# carrackjs
# CarrackJS
JS library for a HTTP Requests
## usage
Example usage with JSON data:
var apiUrlJson = "https://example.com/api/json";
var requestDataJson = {
key1: "value1",
key2: "value2"
};
sendHttpRequest(apiUrlJson, "POST", requestDataJson, function (error, response) {
if (error) {
console.error("Error:", error);
}
else {
console.log("JSON Response:", response);
}
}, "application/json");
Example usage with non-JSON data (e.g., form data):
var apiUrlFormData = "https://example.com/api/formdata";
var formData = new FormData();
formData.append("key1", "value1");
formData.append("key2", "value2");
sendHttpRequest(apiUrlFormData, "POST", formData, function (error, response) {
if (error) {
console.error("Error:", error);
}
else {
console.log("Form Data Response:", response);
}
}, "multipart/form-data");

33
carrack.js Normal file
View File

@ -0,0 +1,33 @@
function sendHttpRequest(url, method, data, callback, contentType = "multipart/form-data") {
var xhr = new XMLHttpRequest();
xhr.open(method, url, true);
xhr.setRequestHeader("Content-Type", contentType);
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
// Successful response
var response;
if (contentType === "application/json") {
response = JSON.parse(xhr.responseText);
} else {
response = xhr.responseText;
}
callback(null, response);
} else {
// Error response
callback(xhr.status, null);
}
}
};
var requestData;
if (contentType === "application/json") {
requestData = JSON.stringify(data);
} else {
requestData = data;
}
xhr.send(requestData);
}