HTML 문서에서 javascript로 http API call을 요청할 수 있다.
<html lang="ko">
<head>
<meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no"/>
<meta charset="utf-8" />
<title>Rest API exam</title>
<script>
async function onLoad() {
console.log('onLoad')
let jsonResponse = await testPost();
console.log(JSON.stringify(jsonResponse));
console.log("testPost done");
let testDiv = document.getElementById('testDiv');
testDiv.textContent = JSON.stringify(jsonResponse);
}
async function testPost() {
const response = await fetch("https://jsonplaceholder.typicode.com/todos", {
method: "POST",
body: JSON.stringify({
userId: 2,
title: "My test api call",
completed: false,
name: "Hoyeong Lee"
}),
headers: {
"Content-type": "application/json; charset=UTF-8"
}
})
const jsonResult = await response.json();
return jsonResult;
}
</script>
</head>
<body onload="onLoad()">
<h1>Test</h1>
<div id="testDiv" style="width:600px;height:250px;"></div>
</body>
</html>
* 위 코드를 실행하는 페이지 보기 → Rest API exam (sparrow-lee.github.io)
Rest API exam
sparrow-lee.github.io
※ 테스트용 API 호출을 해볼 수 있게 제공하는 사이트가 있다.
JSONPlaceholder - Guide (typicode.com)
JSONPlaceholder - Guide
Guide Below you'll find examples using Fetch API but you can JSONPlaceholder with any other language. You can copy paste the code in your browser console to quickly test JSONPlaceholder. Getting a resource fetch('https://jsonplaceholder.typicode.com/posts/
jsonplaceholder.typicode.com
위 링크의 예시에서는 promise를 이용했고, 내가 쓴 예시에서는 비동기 함수를 사용했다.
비동기 동작을 호출하는 함수는 async로 정의하고, 비동기 동작 함수를 쓸 때는 await를 앞에 붙여주면 된다.
그러면, 코드상으로는 순차적으로 개발을 할 수 있는 편하다.
* await를 쓰지 않으면, 비동기 호출을 기다리지 않고 아래 코드들이 먼저 수행되어버릴 수 있다.
브라우저에서 F12를 누르면 console.log로 남긴 로그를 볼 수 있다.
호출결과를 받으면, testDiv 영역에 표시하도록 했다.

로컬 브라우저에서도 fetch를 이용하여, Rest API를 잘 호출할 수 있다. GET, POST 방식 모두 잘 동작하는것 같다.
Github 코드 참고 링크
exam-codes-public/javascript/js-rest-api.html at main · sparrow-lee/exam-codes-public (github.com)
'SW 개발 참고 > Javascript' 카테고리의 다른 글
Bootstrap을 이용하여 손쉽게 예쁜 UI 구성 (0) | 2023.11.19 |
---|---|
window.localStorage 사용으로 이전 선택 저장하기 (0) | 2023.11.19 |
브라우저 Javascript Candle Chart 그리기 (0) | 2023.11.19 |
Javascript JSON 사용하기 (0) | 2023.11.18 |
Javascript Array 배열 자주 쓰는 메서드 (0) | 2023.11.18 |