API(Application Programming Interface)
컴퓨터가 여러 소프트웨어와 상호작용하는 모든 인터페이스
WebAPI: HTTP 기반 인터페이스, 특정 엔드포인트(url)에서 다른소프트웨어로부터 요청된 정보를 응답
XMLHttpRequest
- 최초의 요청 방식
- promise를 지원하지 않음
- 추가 요청시 onload 메소드 내부에 중첩 필요
const req = new XMLHttpRequest();
req.onload = function(){ //오류가 없을 때 실행
console.log("loaded");
const data = JSON.parse(this.responseText); //기본=텍스트 뭉치 형태로 반환, js 객체로 변환 필요
console.log(data);
}
req.onerror = function(){ //오류가 있을 때 실행
console.log("error");
console.log(this);
}
req.open("get", "apiAdress.com/api/1");
req.send();
FETCH
- promise 지원
- 응답 객체의 본문이 구문 분석 되지 않음(ReadableStream)
- 추가 데이터 요청 시 .then으로 선형적 추가
- 연속적 특성
- 첫번째 요청이 실패하면 두번째 요청은 시작되지 않음
fetch("apiAdress.com/api/1")
.then((res) => {
console.log("resolved", res);
return res.json() //전체 출력 원할 시(선택적)
})
.then((data) => {
console.log("JSON DONE", data);
})
.catch((e) => {
consle.log("error", e)
});
//** 비동기 함수로 리팩토링** //
const loadData = async() => {
try{
const res = await fetch("apiAdress/api/1");
const data = await res.json();
}catch (e) {
console.log("error", e);
}
};
loadData();
AXIOS
- JS native library에 해당하지 않아 import 필요
- 자동으로 JSON 형태 구문 해석
const getData = async (id) => {
const config = {headers:{Acceot:'application/json'}};
try{
const res =
await axios.get("apiAdrress.com/api/${id}", config);
//객체에 헤더 정보 함께 전송
console.log(res.data);
}catch(e){
console.log("error", e)
}
};
getData(5);
AJAX
Asynchronous JavaScript and XML
- JSON (Java Script Object Notation) 포맷 사용
- key-value 쌍 구조
- number, String, boolean, array, object …
- undefined = null (undefined 인식 못함)
- JSON.parse(value) => JS 객체 형태로 변환
- JSON.stringfy(value) => JSON 형태로 변환
JSON stands for JavaScript Object Notation JSON is a lightweight data interchange format JSON is language independent JSON is “self-describing” and easy to understand
HTTP protocol
HTTP verbs
GET저장된 데이터 요청POST서버에 데이터 저장 요청delete서버에서 데이터 삭제 요청
HTTP Status Codes
200~요청 성공400 ~client-side error500 ~Server-side error
무료 API 응답 확인 사이트
https://www.postman.com/ (가입필요)
https://hoppscotch.io/
query string
?key1=value1&key2=value2
요청하는 정보에 따라 url에 추가 될 수 있음
HTTP Header
- 요청/응답 시 함께 전달하는 세부 정보
- 기정의된 적절한 형식에 맞춰 전달해야함
(content-type : application/jason)