-
Axios
브라우저, Node.js를 위한 Promise API 활용하는 HTTP 비동기 통신 라이브러리
설치
$ npm install axios
GET 요청
const axios = require('axios') // hello로 요청 axios.get('http://..../hello') // 응답(성공) .then(function (response) { console.log(response) }) // 응답(실패) .catch(function (error) { console.log(error) })
POST 요청
axios.post('http://..../hello', { name: 'world' city: 'seoul' )} .then(function (response) { console.log(response) }) .catch(function (error) { console.log(error) })
응답
{ // data는 서버가 제공한 응답(데이터) data: {}, // status는 서버 응답의 HTTP 상태 코드 status: 200, // statusText는 서버 응답으로 부터의 HTTP 상태 메시지 statusText: 'OK', //`headers 서버가 응답 한 헤더는 모든 헤더 이름이 소문자로 제공 headers: {}, // config는 요청에 대해 `axios`에 설정된 구성(config) config: {}, // reques`는 응답을 생성한 요청 // 브라우저: XMLHttpRequest 인스턴스 // Node.js: ClientRequest 인스턴스(리디렉션) request: {} }
then을 사용하여 다음과 같이 응답을 받을 수 있다.
axios.get('http://..../hello') .then(function (response) { console.log(response.data) console.log(response.status) console.log(response.statusText) console.log(response.headers) console.log(response.config) });
오류 처리
axios.get('http://..../hello') .catch(function (error) { if (error.response) { // 요청이 이루어졌으며 서버가 2xx의 범위를 벗어나는 상태 코드로 응답 console.log(error.response.data) console.log(error.response.status) } else if (error.request) { // 요청이 이루어 졌으나 응답을 받지 못함 console.log(error.request) } else { // 오류를 발생시킨 요청을 설정하는 중에 문제가 발생 console.log('Error', error.message) } console.log(error.config) });
config 옵션 validateStatus를 사용하여 상태 코드 오류 범위를 지정할 수 있다.
axios.get('http://..../hello', { validateStatus: function (status) { // 상태 코드가 300 이상일 경우 거부. 나머지(300보다 작은)는 허용 return status < 300 } })
'Note' 카테고리의 다른 글
웹페이지 Redirect 구현 (0) 2021.01.17 Cookie, Session (0) 2020.12.17 AWS(Amazon Web Services) (0) 2020.12.16 V8 (0) 2020.12.13 서버 사이드 렌더링, 클라이언트 사이드 렌더링 (0) 2020.12.06