Skip to content

Instantly share code, notes, and snippets.

@webuilder240
Created March 20, 2020 11:23
Show Gist options
  • Save webuilder240/10ac8a0be3de84866182bf29f35eb1fa to your computer and use it in GitHub Desktop.
Save webuilder240/10ac8a0be3de84866182bf29f35eb1fa to your computer and use it in GitHub Desktop.
JavaScriptのPromiseベースのHTTPクライアント
class Client {
get(url) {
return this._invoke("GET", url, {});
}
post(url, params = {}) {
return this._invoke("POST", url, params);
}
put(url, params = {}) {
return this._invoke("PUT", url, params);
}
patch(url, params = {}) {
return this._invoke("PATCH", url, params);
}
delete(url, params = {}) {
return this._invoke("DELETE", url, params);
}
_invoke(method, url, params = {}) {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.addEventListener("load", () => {
if (xhr.readyState === 4 && xhr.status < 399) {
resolve(xhr.response);
} else {
reject(new Error(xhr.statusText));
}
});
xhr.open(method, url, true);
xhr.addEventListener("error", () => {
reject(new Error(xhr.statusText));
});
xhr.setRequestHeader( 'Content-Type', 'application/x-www-form-urlencoded' );
const requestBody = this._request_body_builder(params);
xhr.send(requestBody);
});
}
_request_body_builder(params) {
if (!params) {
return null;
}
const result = [];
for (let name in params) {
const value = params[name];
const param = encodeURIComponent(name) + "=" + encodeURIComponent(value);
result.push(param);
}
return result.join("&").replace("/%20/g", "+");
}
}
const client = new Client();
client.get("https://httpstat.us/200").then(response => {
console.log(response);
}).catch(e => {
console.error(e);
});
client.post("https://httpstat.us/500?sleep=1000").then(response => {
console.log(response);
}).catch(e => {
console.error(e);
});
(async () => {
console.log(await client.post("https://httpstat.us/201", {hello: "world", params: 100}));
})();
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Client Test</title>
</head>
<body>
<h1>
Check Console !
</h1>
<script src="./client.js"></script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment