본문 바로가기
IT 공부/프런트엔드_기록용

AJAX API

by 랜턴K 2025. 10. 26.
반응형

Postman ; API 테스트하는 웹 서비스 

Hopp

 

GET; 정보를 가져옴 

POST ; 데이터를 보냄 

 

Status code

- 2로 시작하는 경우 ; 정상처리 됨 

- 3로 시작하는 경우 ; 리디렉션 경우 

- 4로 시작하는 경우 ; 클라이언트 측에서 잘못되었을 때 코드 

- 5로 시작하는 경우 ; 서버 사이드 오류

- 개발자도구 네트워크 탭에서도 확인 가능 

 

쿼리 스트링

- URL 

- URL/:id (변수가 들어가는 경우) ; : 대신 {}를 쓰기도 한다. 

- URL?sort=desc&color-green ; 쿼리 스트링 

 

HTTP 헤더 

- 요청과 함께 정보를 전달하는 부수적 방식

 

MAKING XHRs

- XHR = XMLHttpRequest

- 프로미스나 비동기 함수를 지원 X 

- 연속적인 요청이 종속 관계가 필요할 때, 콜백을 여러개 사용 > 중첩 > 코드 복잡 

const req = new XMLHttpRequest();

req.onload = function(){
    console.log("IT LOADED");
    const data = JSON.parse(this.responseText);
    console.log(data);
}
req.onerror = function(){
    console.log("ERROR");
    console.log(this);
}
req.send();

 

Fetch 

- 패치 첫함수는 프로미스를 반환함

- 일단 응답을 받은 걸로 실행됨 

- 데이터 다운에 대한 건 비동기로 실행되므로 

  별도로 json() 함수를 통해 데이터를 받음 (양동이에 물 받듯) 

- 다 받아지면, 두번째 프로미스가 싫애 


    .then((res)=>{
        console.log("resolved!", res)
        return res.json();
    })
    .then((data)=> {
        console.log(data);
    })
    .catch((err)=>{
        console.log("rejected!", err)
    })
const loadStarWarsPeople = async () => {
    try{        
        const request = await fetch('https://swapi.dev/api/people/1');
        const data  = await request.json();
        console.log(data);

        const request2 = await fetch('https://swapi.dev/api/people/2');
        const data2  = await reqeust2.json();
        console.log(data2);
    } catch (e) {
        console.log('error type : ',e);
    }
};

 

Axios

- js 표준은 아님 -> 따로 라이브러리 다운받고 사용해야 함 

- fetch는 비동기 처리에 대해 기다려야 했지만

- Axios에서는 axios.get으로 한번에 처리할 수 있음

 

Axios와 헤더 세팅하기 

- config 변수에 headers : {key : value} 를 입력하여

같이 보낼 수 있다.  

const form = document.querySelector('#searchFrom');
const container = document.querySelector('#image-container');



form.addEventListener('submit', async function (e){
    e.preventDefault();

    container.innerHTML = '';

    const searchTerm =form.elements[0].value;
    const config = {params : {q : searchTerm}};
    const res = await axios.get(`https://api.tvmaze.com/search/shows`, config);

    makeImages(res.data)
})

const makeImages = (RESULTS) => {
    for (let result of RESULTS){
        if (result.show.image){
            const img = document.createElement('img');
            img.src = result.show.image.medium;
            container.append(img);    
        }
    }
}
반응형