[React] Axios, API
Axios는 Ajax같은 자바스크립트 라이브러리임
우리는 axios는 terminal에서 설치하면된다
프로젝트 경로로 들어가서 터미널에서 명령어 입력
npm install axios
설치하면 node_module 폴더에 추가되고
어쩌고저쩌고 warning 메세지가 뜨는데 앱은 실행됨
Unsplash API를 사용할건데 이건 파라미터로 단어 넘기면 이미지를 리턴해주는 라이브러리임
https://unsplash.com/documentation#location
https://unsplash.com/documentation#search-photos
Unsplash API Documentation | Free HD Photo API | Unsplash
Getting started This document describes the resources that make up the official Unsplash JSON API. If you have any problems or requests, please contact our API team. Creating a developer account To access the Unsplash API, first join. Registering your appl
unsplash.com
location에 보면 주소 나와있음
그럼 우리는 axios로 이렇게 요청해보겠습니당
오! ajax보다 사용하기 편하게 되어있음ㅋ
* api 요청하기
- api.js
import axios from 'axios';
const searchImage = async() =>{
const response = await axios.get('https://api.unsplash.com/search/photos',{
headers:{
Authorization:'Client-ID YOURID'
},
params:{
query:'cars'
}
});
console.log(response);
return response;
}
export default searchImage;
응답을 잘 받아오는지 11행에서 response를 콘솔로 출력해보구여
async는 비동기임. 비동기 알져? 비동기에는 await 사용해야함
api request를 하고나서 response를 받는데 시간이 걸리는데
동기화(sync)를 해버리면 응답기다리는동안 다음으로 넘어가지 않는데여
비동기(async)로 하면 기다리는동안 다른작업을 수행하고 응답이 오면 그때 처리하게 됩니당. 그럼 훨씬 빠르겠쪄?
암튼 api.js가 잘 작동되는지 index.js에서 api.js의 searchImage를 import해서 searchImage(); 함수를 호출해주면
ㅇㅇ 응답 잘 받음 굿
그럼 이걸 활용해서 검색어를 입력하면 api를 통해 이미지를 받고 이미지를 뿌려주는 앱을 만들어 볼 거싱ㅂ니당