Axios 바로가기
Yes Or No? api 바로가기
- 웹 브라우저와 Node.js를 위한 HTTP 비동기 통신 라이브러리.
- 백엔드와 프론트엔드 간 통신을 쉽게 하기 위해 사용되는 것으로 Ajax처럼 사용되는 것.
- 비동기 통신 라이브러리를 사용하지 않으면 모든 코드가 순차적으로 처리되어야 하므로 코드의 순서를 신경써서 작성해야 한다.
- 운영 환경에 따라 브라우저의 XMLHttpRequest 객체 또는 Node.js의 http API 사용
- Promise(ES6) API 사용 + Promise 객체를 반환한다
- 요청과 응답 데이터의 변형
- HTTP 요청 취소
- HTTP 요청과 응답을 JSON 형태로 자동 변경
- data 속성을 사용하며, data는 object를 포함한다.
- 자동으로 JSON데이터 형식으로 변환된다.
axios.request(config)
axios.get(url[, config])
axios.delete(url[, config])
axios.head(url[, config])
axios.options(url[, config])
axios.post(url[, data[, config]])
axios.put(url[, data[, config]])
axios.patch(url[, data[, config]])
axios({
method: "get", // 통신 방식
url: "www.naver.com", // 서버
headers: {'X-Requested-With': 'XMLHttpRequest'} // 요청 헤더 설정
params: { api_key: "1234", langualge: "en" }, // ?파라미터를 전달
responseType: 'json', // default
maxContentLength: 2000, // http 응답 내용의 max 사이즈
validateStatus: function (status) {
return status >= 200 && status < 300; // default
}, // HTTP응답 상태 코드에 대해 promise의 반환 값이 resolve 또는 reject 할지 지정
proxy: {
host: '127.0.0.1',
port: 3000,
auth: {
username: 'Joruneybonbon',
password: '1111'
}
}, // proxy서버의 hostname과 port를 정의
maxRedirects: 5, // node.js에서 사용되는 리다이렉트 최대치를 지정
httpsAgent: new https.Agent({ keepAlive: true }), // node.js에서 https를 요청을 할때 사용자 정의 agent를 정의
})
.then(function (response) {
// response Action
});
axios({
method: "get", // 통신 방식
url: "www.naver.com", // 서버
})
.then(function(response) {
console.log(response.data) // 서버가 제공한 응답(데이터)
console.log(response.status) // `status`는 서버 응답의 HTTP 상태 코드
console.log(response.statusText) // `statusText`는 서버 응답으로 부터의 HTTP 상태 메시지
console.log(response.headers) // headers` 서버가 응답 한 헤더는 모든 헤더 이름이 소문자로 제공
console.log(response.config) // `config`는 요청에 대해 `axios`에 설정된 구성(config)
})
// 지정된 ID를 가진 유저에 대한 요청
axios.get('https://yesno.wtf/api')
.then(function (response) {
// 성공 핸들링
console.log(response);
})
.catch(function (error) {
// 에러 핸들링
console.log(error);
})
.finally(function () {
// 항상 실행되는 영역
});
// 선택적으로 위의 요청은 다음과 같이 수행될 수 있습니다.
axios.get('/user', {
params: {
ID: 12345
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
})
.finally(function () {
// 항상 실행되는 영역
});
// async/await 사용을 원한다면, 함수 외부에 `async` 키워드를 추가하세요.
async function getUser() {
try {
const response = await axios.get('/user?ID=12345');
console.log(response);
} catch (error) {
console.error(error);
}
}