이전글에서 Postman을 설치하고 Mock Server를 만들었다!
이번에는 API를 Mock Server에 등록하고 테스트해보려고 한다.
Add request를 선택하여 API를 추가했다.
여기서 API 이름은 list로 해주었고, path에는 {{url}}/list를 입력했다.
example을 추가하여 이것 역시 {{url}}/list로 path를 설정해 주고 save를 하였다.
이후 run을 하여 실행시키면
콘솔창에 GET https 주소를 찾을 수 있다.
주소를 입력하면 위처럼 잘 나타나는 것을 확인할 수 있다.
Vue.js 프로젝트에서 이것을 사용해 보자.
npm install axios --save
터미널에 위의 명령어를 입력하여 axios를 설치해 준다.
axios는 서버와 데이터를 송수신할 수 있는 HTTP 비동기 통신 라이브러리이다.
그리고 axios를 쓰기 위한 mixins.js 파일을 생성한다.
import axios from 'axios';
export default {
methods: {
async $api(url, method, data) {
return (await axios({
method: method,
url,
data
}).catch(e => {
console.log(e);
})).data;
}
}
}
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import mixins from './mixins'
const app = createApp(App)
app.use(router)
app.mixin(mixins);
app.mount('#app')
main.js 파일에도 mixins.js를 사용할 수 있도록 코드를 추가해 준다.
그리고 API를 사용하려고 다음과 같은 vue를 작성했다.
<template>
<div>
<table>
<thead>
<tr>
<th>학번</th>
<th>이름</th>
<th>나이</th>
<th>성별</th>
</tr>
</thead>
<tbody>
<tr :key="i" v-for="(info, i) in infoList">
<td>{{info.id}}</td>
<td>{{info.name}}</td>
<td>{{info.age}}</td>
<td>{{info.gender}}</td>
</tr>
</tbody>
</table>
</div>
</template>
<script>
export default {
data() {
return {
infoList: []
};
},
created() {
this.getList();
},
methods: {
async getList() {
this.infoList = await this.$api("GET https 주소를 여기에 입력","get");
// 여기에서는 다음 주소와 같은 형식이었다.
// https://4092d5b4-b228-41da-afae-32797fbb2d5c.mock.pstmn.io/list
}
}
}
</script>
<style scoped>
table {
font-family: arial, sans-serif;
border-collapse: collapse;
width: 100%;
}
td, th {
border: 1px solid #dddddd;
text-align: left;
padding: 8px;
}
</style>
Mock Server로 API를 호출하여 리스트 렌더링 처리를 할 수 있음을 확인했다.
나머지 부분은 읽고나서 새로 만들며 쓸 예정..
'Vue.js' 카테고리의 다른 글
postman을 사용하여 API 테스트하기 - 1 (0) | 2023.03.07 |
---|---|
데이터 바인딩 (0) | 2023.03.01 |
Vue.js와 Spring Boot 연결 (0) | 2023.02.19 |