12. AJAX 및 Axios 프레임워크
12.1 AJAX 기본 개념
AJAX(Asynchronous JavaScript and XML)는 웹 페이지를 완전히 재로드하지 않고도 백그라운드에서 서버와 데이터를 교환할 수 있는 기술입니다. 이 기술은 사용자 경험을 향상시키기 위해 네트워크 통신을 비동기적으로 수행합니다.
12.1.1 AJAX 작동 원리
- XMLHttpRequest 객체 생성: 서버와의 데이터 교환을 위한 핵심 컴포넌트
- 요청 전송: 생성된 객체를 통해 서버에 요청을 보냅니다
- 서버 처리: 요청을 받은 서버가 데이터를 생성합니다
- 응답 수신: XMLHttpRequest가 서버의 응답을 받습니다
- 페이지 업데이트: JavaScript를 사용해 특정 영역만 업데이트합니다
12.1.2 제3자 데이터 인터페이스
제3자 API는 서비스 제공자 외부에서 제공하는 데이터 접근 인터페이스로, HTTP 요청을 통해 데이터를 가져올 수 있습니다. 대표적인 예로 날씨 정보나 뉴스 데이터를 들 수 있습니다.
12.1.3 AJAX 예제
<body>
<script>
const requestObj = new XMLHttpRequest();
requestObj.open('get', 'https://apis.tianapi.com/tianqi/index?key=yourkey&city=101020100&type=1');
requestObj.send(null);
requestObj.onreadystatechange = function() {
if(requestObj.readyState === 4 && requestObj.status === 200) {
console.log(requestObj.responseText);
}
}
</script>
</body>12.1.4 비동기 특성
AJAX의 핵심 특징은 UI 스레드를 차단하지 않으며, 이벤트 기반으로 처리됩니다. 이로 인해 사용자는 페이지 로딩 중에도 다른 작업을 수행할 수 있습니다.
12.2 Axios 프레임워크
Axios는 Promise 기반의 HTTP 요청 라이브러리로, 브라우저와 Node.js에서 사용 가능합니다. 요청/응답 인터셉터, 자동 JSON 변환 등의 기능을 제공합니다.
12.2.1 GET 및 POST 요청
GET 요청은 데이터 조회에 사용되며, POST 요청은 데이터 전송에 적합합니다. 파라미터 전달 방식과 보안 특성이 다릅니다.
12.2.2 Axios GET 요청 예제
<script>
axios.get('https://apis.tianapi.com/tianqi/index?key=yourkey&city=101020100&type=1')
.then(response => console.log(response))
.catch(error => console.error(error));
</script>12.2.3 Axios POST 요청
<script>
function formatParams(data) {
return Object.entries(data).map(([k, v]) =>
`${encodeURIComponent(k)}=${encodeURIComponent(v)}`).join('&');
}
axios.post('https://apis.tianapi.com/tianqi/index', formatParams({
key: 'yourkey',
city: '101020100',
type: '1'
}))
.then(response => console.log(response))
.catch(error => console.error(error));
</script>12.2.4 응답 구조
<script>
axios.post('https://apis.tianapi.com/tianqi/index', formatParams({
key: 'yourkey',
city: '101020100',
type: '7'
}))
.then(response => {
const weatherList = response.data.result.list;
const container = document.getElementById('container');
container.innerHTML = weatherList.map(item =>
`날짜: ${item.date}, 날씨: ${item.weather}`).join('<br>');
});
</script>12.2.5 전역 설정
axios.defaults.baseURL = 'https://apis.tianapi.com/';
axios.post('tianqi/index', formatParams({ key: 'yourkey' }))12.2.6 인터셉터
axios.interceptors.request.use(config => {
console.log('요청 전달');
return config;
});
axios.interceptors.response.use(response => {
console.log('응답 처리');
return response;
});12.3 Vue-cli에서 Axios 사용
<template>
<div>
<h1>상해 7일 날씨</h1>
<ul>
<li v-for="item in weatherData" :key="item.date">
<p>{{ item.date }} {{ item.week }} {{ item.weather }}</p>
</li>
</ul>
</div>
</template>
<script setup>
import axios from 'axios';
import { ref } from 'vue';
const weatherData = ref([]);
axios.get('https://apis.tianapi.com/tianqi/index?key=yourkey&city=101020100&type=7')
.then(response => weatherData.value = response.data.result.list);
</script>12.4 Vue-cli에서 크로스 오리진 처리
12.4.1 크로스 오리진 개념
브라우저의 동일원칙(Same-Origin Policy)에 따라, 다른 원(프로토콜, 도메인, 포트) 간의 요청은 차단됩니다. 이를 해결하기 위한 방법으로 CORS, JSONP, 프록시 서버 등이 있습니다.
12.4.2 Vue-cli 프록시 설정
module.exports = {
devServer: {
proxy: {
'/api': {
target: 'http://v.juhe.cn',
changeOrigin: true,
pathRewrite: { '^/api': '' }
}
}
}
}axios.get('/api/toutiao/index?key=yourkey')