김 양의 멋따라 개발따기
2022.08.14./WIL Axios 본문
1. Axios 란?
- Axios는 node.js와 브라우저를 위한 Promise 기반 HTTP 클라이언트 입니다.
- 그것은 동형 입니다(동일한 코드베이스로 브라우저와 node.js에서 실행할 수 있습니다).
- 서버 사이드에서는 네이티브 node.js의 http 모듈을 사용하고,
클라이언트(브라우저)에서는 XMLHttpRequests를 사용합니다.
2. Axios의 특징
- 브라우저를 위해 XMLHttpRequests 생성
- node.js를 위해 http 요청 생성
- Promise API를 지원
- 요청 및 응답 인터셉트
- 요청 및 응답 데이터 변환
- 요청 취소
- JSON 데이터 자동 변환
- XSRF를 막기위한 클라이언트 사이드 지원
3. Axios 설치
$ yarn add axios
$ npm install axios
4. Axios 예
const axios = require('axios');
// 지정된 ID를 가진 유저에 대한 요청
axios.get('/user?ID=12345')
.then(function (response) {
// 성공 핸들링
console.log(response);
})
.catch(function (error) {
// 에러 핸들링
console.log(error);
})
.then(function () {
// 항상 실행되는 영역
});
// 선택적으로 위의 요청은 다음과 같이 수행될 수 있습니다.
axios.get('/user', {
params: {
ID: 12345
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
})
.then(function () {
// 항상 실행되는 영역
});
// async/await 사용을 원한다면, 함수 외부에 `async` 키워드를 추가하세요.
async function getUser() {
try {
const response = await axios.get('/user?ID=12345');
console.log(response);
} catch (error) {
console.error(error);
}
}
// POST 요청 전송
axios({
method: 'post',
url: '/user/12345',
data: {
firstName: 'Fred',
lastName: 'Flintstone'
}
});
// node.js에서 GET 요청으로 원격 이미지 가져오기
axios({
method: 'get',
url: 'http://bit.ly/2mTM3nY',
responseType: 'stream'
})
.then(function (response) {
response.data.pipe(fs.createWriteStream('ada_lovelace.jpg'))
});
'TIL' 카테고리의 다른 글
22.09.20./TIL(로컬 스토리지, 세션 스토리지, 쿠키) (0) | 2022.09.20 |
---|---|
22.09.29.TIL/타입스크립트(TypeScript) (0) | 2022.09.19 |
2022.08.02. TIL (Git!) (0) | 2022.08.03 |
2022.07.31. WIL (0) | 2022.07.31 |
2022.07.29. TIL 라우터 (0) | 2022.07.30 |