Skip to content

Instantly share code, notes, and snippets.

@shiro01
Created May 30, 2018 06:24
Show Gist options
  • Save shiro01/a2aabc4016536be63b4081d570cee496 to your computer and use it in GitHub Desktop.
Save shiro01/a2aabc4016536be63b4081d570cee496 to your computer and use it in GitHub Desktop.
API call made with APIGateway from HTML with fetch.
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>fetch_api</title>
</head>
<body>
<input type="button" value="GET" onclick=submitGetApi()>
<div id="getResult"></div>
<input type="button" value="POST" onclick=submitPostApi()>
<div id="postResult"></div>
<!--
https://developer.mozilla.org/ja/docs/Web/API/Fetch_API/Using_Fetch
https://docs.aws.amazon.com/ja_jp/apigateway/latest/developerguide/how-to-cors.html#how-to-cors-console
-->
<script type="text/javascript">
function submitGetApi() {
url = "https://your-api.region.amazonaws.com/get-api"; // Use API Gateway. This api is doing enable CORS.
fetch(url, {
mode: 'cors'
}).then(function(response) {
return response.json();
}).then(function(json) {
const json_obj = JSON.parse(json);
document.getElementById("getResult").textContent=JSON.stringify(json_obj);
});
}
function submitPostApi() {
const data = {"request": "aaaa"};
const url = "https://your-api.region.amazonaws.com/post-api"; // Use API Gateway. This api is doing enable CORS.
// var myHeaders = new Headers();
// myHeaders.append("Content-Type", "text/plain");
const myHeaders = new Headers({'Content-Type': 'text/plain'});
fetch(url, {
mode: 'cors',
method: 'POST',
body: JSON.stringify(data),
headers: myHeaders
}).then(function(response) {
console.log(response.status);
return response.json();
}).then(function(json) {
const json_obj = JSON.parse(json);
document.getElementById("postResult").textContent=JSON.stringify(json_obj);
});
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment