fetch 함수에 이어서 자바스크립트 내장 함수가 아닌 axios에 대해 알아보려고 한다.
우선 fetch는 구문 분석이 필요하다는 단점이 있었다.
axios는 구문 분석을 따로 하지 않아도 된다는 장점이 있다.
내장함수가 아니기 때문에 외부에서 추가 빌드가 필요하다.
https://github.com/axios/axios
GitHub - axios/axios: Promise based HTTP client for the browser and node.js
Promise based HTTP client for the browser and node.js - GitHub - axios/axios: Promise based HTTP client for the browser and node.js
github.com
깃허브 하단에 보면 CDN 부분이 있는데 그대로 가져와서 스크립트에 붙여서 사용하면 된다.
그 밑에 example로 http 요청 예시들이 나와있다.
// Make a request for a user with a given ID
axios.get('/user?ID=12345')
.then(function (response) {
// handle success
console.log(response);
})
.catch(function (error) {
// handle error
console.log(error);
})
.finally(function () {
// always executed
});
// Optionally the request above could also be done as
axios.get('/user', {
params: {
ID: 12345
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
})
.finally(function () {
// always executed
});
// Want to use async/await? Add the `async` keyword to your outer function/method.
async function getUser() {
try {
const response = await axios.get('/user?ID=12345');
console.log(response);
} catch (error) {
console.error(error);
}
}
get을 하고 싶으면 axios 뒤에 .get
post면 .post 를 쓰면 된다.
api를 사용하다보면
header 영역이 있는데
모든 API 끝점은 각각의 브라우저 URL을 따르지만 제공된 HTTP 헤더를 기반으로 API에 더 적합하도록 응답 형식을 조정합니다 라고 나와 있다.
우리는 json 이 포함된 엔드포인트가 필요하기 때문에 헤더 설정이 필요하다.
axios.get('https://icanhazdadjoke.com/', {headers: {}});
이런 식으로 사용해도 되고
상수로 지정해줘서 사용해도 된다.
const config = { header:{Accept:'application/json'}}
axios.get('https://icanhazdadjoke.com/', config);
콘솔에서 확인해보니
잘 바뀐 모습이다
이제 data가 잘 받아졌으니 활용하면 된다.
'javascript' 카테고리의 다른 글
[JS] class 확장과 super (0) | 2023.04.19 |
---|---|
[JS] 객체 지향 프로그래밍(OOP) 팩토리 함수, 생성자 함수, class (0) | 2023.04.18 |
[JS] fetch 와 XHR (0) | 2023.04.16 |
[JS] JSON 파싱 (0) | 2023.04.11 |
[JS] async, await (0) | 2023.04.09 |