서버는 그냥 요청하면 데이터주는 간단한 프로그램이라고 생각하면 된다.
예를 들어 네이버 웹툰 서버라고 한다면, 웹툰 달라고 하면 주는 프로그램인 것이다.
근데 서버에게 데이터를 요청하려면 GET 요청 / POST 요청 이라는 방법을 꼭 써야하는데,
GET
은 데이터를 가져올 때 사용하며 서버가 요구하는 URL
을 적어야 한다.
POST
는 서버로 데이터를 보낼 때 사용하고 역시 서버가 요구하는 URL
을 적어야 한다.
fetch
라는 자바스크립트 기본함수를 써도 되는데, 호환성 때문에 axios
를 자주 쓰게 될 것이다.
npm
npm install axios
yarn
yarn add axios
import axios from 'axios';
axios.get('서버URL').then( 결과 => {
// GET요청 성공시 실행할 코드~~
console.log(결과);
})
GET
요청으로 가져온 데이터는 결과
라는 파라미터에 담겨있다.
또한 ajax요청이 실패시 특정 코드를 실행하고 싶으면 .catch
안에 적으면 된다.
URL
을 잘못 쓰거나 서버가 다운되거나 그러면 ajax 요청이 실패할 수 있으니 주의!
import axios from 'axios';
axios.get('서버URL').then( 결과 => {
// GET요청 성공시 실행할 코드~~
}).catch( ()=>{
// 실패시 실행할 코드
})
import axios from 'axios';
axios.post('서버URL', '보낼데이터').then( 결과 => {
// POST요청 성공시 실행할 코드~~
}).catch( ()=>{
// 실패시 실행할 코드
})
POST
요청은 서버로 원하는 데이터를 전송할 수 있다. string, object 다 가능하다!
더보기 버튼을 누르면 추가 게시물을 볼 수 있게 만들어주게 만들어보자!
우선 App.vue에서 axios
를 이용하여 데이터를 얻어보자..
순차적으로 설명은 주석에 써놓았으니 잘 읽어주세요 ^*^
import Container from "./components/Container.vue";
import boards from "./data/boards";
// azios를 import하고..
import axios from "axios";
export default {
name: "App",
components: {
Container,
},
data() {
return {
boards,
};
},
methods: {
// 버튼을 눌럿을 때, 실행할 함수에서 axios를 이용해 GET방식으로 데이터를 와서..
onClickMore() {
axios
.get("https://codingapple1.github.io/vue/more1.json")
.then((result) => {
// 파라미터에 담긴 데이터를 콘솔로 찍어서 확인도 하고..
console.log(result);
// 글목록 데이터(boards.js)에 GET받은 데이터(result)를 추가하면..
this.boards.push(result.data);
});
},
},
};
<template>
<div>
<div class="header">
<ul class="header-button-left">
<li>Cancel</li>
</ul>
<ul class="header-button-right">
<li>Next</li>
</ul>
<img src="./assets/logo.png" class="logo" />
</div>
<Container :boards="boards" />
<!-- 클릭시 axios를 이용해 받은 데이터를 기존 데이터 배열에 추가하는 함수가 실행됨 -->
<button @click="onClickMore">더보기</button>
<div class="footer">
<ul class="footer-button-plus">
<input type="file" id="file" class="inputfile" />
<label for="file" class="input-plus">+</label>
</ul>
</div>
</div>
</template>
그런다음 App.vue의 템플릿 부분에서 버튼에 click 시, 일어날 함수를 바인딩 해주면 끝!
잘 보고갑니다.