JavaScript API 호출방법

1000명진·2023년 10월 14일
0
post-thumbnail

1. jQuery AJAX

//jQuery 불러오기
<script src="https://code.jquery.com/jquery-3.6.0.js" integrity="sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk=" crossorigin="anonymous"></script>
//$.ajax()메서드 사용해서 요청
<script>
	$(document).ready(function() {
		$.ajax({
			url: 'https://www.fruityvice.com/api/fruit/all',
			type: 'GET',
			success: function(result) {
				console.log(result);
			}
		})
	});
</script>

2. XML HTTP Request

  • 모든 최신 브라우저는 서버에 데이터를 요청하기 위해 XMLHttpRequest 객체를 지원함(ES6제외)
var request = new XMLHttpRequest();
request.open('GET', 'API주소');
request.send();
request.onload = function() {
	console.log(JSON.parse(request.response));
}

3. Fetch API

  • Fetch API는 비동기 방식으로 리소스를 가져오기 위한 인터페이스를 제공함
  • Promise를 반환
  • fetch는 ES6부터 자바스크립트의 내장 라이브러리로 들어왔습니다.
fetch('API주소')
.then(res => res.json())
.then(data => console.log(data));

4. Axios

  • HTTP 요청을 만들기 위한 오픈 소스 라이브러리입니다.
  • 브라우저와 Node.js 모두에서 작동을 합니다.
  • 외부 CDN을 사용하여 HTML에 포함시킬 수 있습니다.
  • Promise를 반환
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script>
	axios.get('API주소')
		.then(res => res.data)
        .then(data => console.log(data));
</script>
profile
심심할때쓰는 기록장

0개의 댓글

Powered by GraphCDN, the GraphQL CDN