서버에서 데이터를 가져올 때 ajax 사용
유저는 server에게 get/post 요청을 통해 데이터를 요청한다.
Get 요청 : 데이터 서버에서 가져올 때
Post 요청 : 서버로 데이터를 보낼 때
ajax를 쓰면 새로고침 없이도 GET POST 요청이 가능하다.
1. axios 라이브러리를 쓰든가
npm install axios
2. 기본 fetch 함수 쓰든가
1번을 주로 사용!!
import axios from 'axios';
axios.get('서버URL').then( 결과 => {
GET요청 성공시 실행할 코드~~
console.log(결과);
})
이렇게 쓰면 원하는 URL로 GET요청을 할 수 있다.
그리고 .then() 안에 function(){} 콜백함수를 추가해주면 되는데
그 안에는 GET요청 성공시 실행할 코드를 적으면 된다.
GET요청으로 가져온 데이터는 '결과'라는 파라미터에 담겨있다.
import axios from 'axios';
axios.get('서버URL').then( 결과 => {
GET요청 성공시 실행할 코드~~
}).catch( ()=>{
실패시 실행할 코드
})
ajax요청이 실패시 특정 코드를 실행하고 싶으면 .catch 안에 적으면 된다.
URL을 잘못 쓰거나 서버가 다운되거나 그러면 ajax 요청이 실패할 수 있다.
import axios from 'axios';
axios.post('서버URL', '보낼데이터').then( 결과 => {
POST요청 성공시 실행할 코드~~
}).catch( ()=>{
실패시 실행할 코드
})
POST 요청을 보낼 수도 있는데 이는 서버로 원하는 데이터를 전송할 수 있다. 문자, object 다 가능!!
실제 사용한 코드는 아래와 같다.
<template>
<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>
<NewContainer :post="post" />
<!-- 클릭시 axios를 이용해 받은 데이터를 기존 데이터 배열에 추가하는 함수가 실행됨 -->
<button @click="more">더보기</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>
</template>
<script>
import NewContainer from "@/components/NewContainer.vue";
import insta from "../src/assets/insta";
import axios from "axios";
axios.post();
export default {
name: 'App',
data(){
return {
post : insta
// insta라는 이름으로 불러온 데이터를 post라는 이름으로 저장
}
},
components: {
NewContainer : NewContainer
},
methods : {
// 버튼을 눌렀을 때, 실행할 함수에서 axios를 이용해 GET방식으로 데이터를 와서..
more(){
axios.get('https://codingapple1.github.io/vue/more1.json')
.then((result)=>{
//요청성공 시 실행할 코드
console.log(result.data);
// 글목록 데이터(insta.js)에 GET받은 데이터(result)를 추가하면..
this.post.push(result.data);
})
}
},
}
this.post.push(result.data); 에서 현재 post라는 데이터의
앞부분에 추가할 경우에는 unshift(),
뒷부분에 추가할 경우 push()를 사용한다.