npm install --save axios
믹스 1) api.js
믹스2) TimeSpentByVisitors.js
export default {
data() {
return {
startTime: 0,
endTime: 0,
stayTime: 0
}
},
methods: {
getCurrentDate() {
const date = new Date();
var year = date.getFullYear().toString();
let month = date.getMonth() + 1;
month = month < 10 ? '0' + month.toString() : month.toString();
let day = date.getDate();
day = day < 10 ? '0' + day.toString() : day.toString();
let hour = date.getHours();
hour = hour < 10 ? '0' + hour.toString() : hour.toString();
let minites = date.getMinutes();
minites = minites < 10 ? '0' + minites.toString() : minites.toString();
let seconds = date.getSeconds();
seconds = seconds < 10 ? '0' + seconds.toString() : seconds.toString();
return year + month + day + hour + minites + seconds;
}
},
mounted() {
this.startTime = parseInt(this.getCurrentDate());
console.log("믹스인 mounted 시작 시간: " + this.startTime);
},
unmounted() {
this.endTime = parseInt(this.getCurrentDate());
console.log("믹스인 unmounted : 종료 시간" + this.endTime);
this.stayTime = this.endTime - this.startTime;
console.log("믹스인 unmounted : 페이지 머문 시간" + this.stayTime);
},
}
Data.vue
<template>
<div>
<h2>axios 목록 불러오기</h2>
<table>
<thead>
<tr>
<th>제품명</th>
<th>가격</th>
<th>카테고리</th>
<th>배송료</th>
</tr>
</thead>
<tbody>
<tr v-for="(product, i) in prodectList" :key="i">
<td>{{product.product_name}}</td>
<td>{{product.price}}</td>
<td>{{product.category}}</td>
<td>{{product.delivery_price}}</td>
</tr>
</tbody>
</table>
</div>
</template>
<script>
import ApiMixin from '@/mixins/api.js'
import TimeSpentByVisitors from '@/mixins/TimeSpentByVisitors.js'
export default {
mixins:[ApiMixin,TimeSpentByVisitors],//사용할 믹스인 파일을 배열로 등록
data(){
return{
prodectList:[],
prodectList2:[]
}
},
async mounted(){
this.prodectList2 = await this.$callAPI("https://e9c0112a-ba7d-47e5-8d08-efcc00f358d2.mock.pstmn.io/list", "get");
console.log("컴포넌트 mounted");
console.log("prodectList2");
console.log(this.prodectList2);
},
created(){
this.getList();
},
methods:{
async getList(){
this.prodectList=await this.$api("https://e9c0112a-ba7d-47e5-8d08-efcc00f358d2.mock.pstmn.io/list", "get");
}
},
unmounted(){
console.log("컴포넌트 unmounted");
},
}
</script>
<style scoped>
table{
font-family: Arial, Helvetica, sans-serif;
border-collapse: collapse;
width: 100%;
}
td, th{
border: 1px solid #dddddd;
text-align: left;
padding: 8px;
}
</style>
예 )
1)plugins/axios.js
import Vue from 'vue'
import axios from 'axios'
const firebaseAPI = axios.create({
baseURL: 'http://localhost:5001/vue-test-841ad/us-central1/',
timeout: 5000,
headers: { 'X-Custom-Header': 'foobar' }
});
// 요청 인터셉터 추가하기
firebaseAPI.interceptors.request.use(function (config) {
// 요청이 전달되기 전에 작업 수행
//헤더만 가로채서 인증 토큰만 변경후 서버로 보낸다.
config.headers.authorization = Math.random();
return config;
}, function (error) {
// 요청 오류가 있는 작업 수행
return Promise.reject(error);
});
Vue.prototype.$axios = firebaseAPI
2)axios.vue (vuetify 사용)
!<template>
<v-container fluid grid-list-md>
<v-layout row warp>
<v-flex xs12 >
<v-toolbar color="primary" dark>
axios eg
</v-toolbar>
</v-flex>
</v-layout>
<v-layout row warp>
<v-flex xs4>
<v-card>
<v-card-title primary-title>
creat
</v-card-title>
<v-card-text>
<v-textarea v-model="textCreate" row="10"></v-textarea>
</v-card-text>
<v-card-actions>
<v-btn color="primary" @click="axiosCreate">submit</v-btn>
</v-card-actions>
</v-card>
</v-flex>
<v-flex xs4>
<v-card>
<v-card-title primary-title>
read
</v-card-title>
<v-card-text>
<v-textarea v-model="textRead" row="10"></v-textarea>
</v-card-text>
<v-card-actions>
<v-btn color="primary" @click="axiosRead">submit</v-btn>
</v-card-actions>
</v-card>
</v-flex>
<v-flex xs4>
<v-card>
<v-card-title primary-title>
update
</v-card-title>
<v-card-text>
<v-textarea v-model="textUpdate" row="10"></v-textarea>
</v-card-text>
<v-card-actions>
<v-btn color="primary" @click="axiosUpdate">submit</v-btn>
</v-card-actions>
</v-card>
</v-flex>
<v-flex xs4>
<v-card>
<v-card-title primary-title>
delete
</v-card-title>
<v-card-text>
<v-textarea v-model="textDelete" row="10"></v-textarea>
</v-card-text>
<v-card-actions style="display: flex; justify-content: flex-end;">
<v-btn color="primary" @click="axiosDelete">submit</v-btn>
</v-card-actions>
</v-card>
</v-flex>
</v-layout>
</v-container>
</template>
<script>
export default {
data(){
return{
textCreate:'',
textRead:'',
textUpdate:'',
textDelete:'',
}
},
methods:{
async axiosCreate(){
//this.$toasted.global.error('ee');
const res= await this.$axios.post('test');
this.textCreate=res.data;
},
async axiosRead(){
const res= await this.$axios.get('test/12');
this.textRead=res.data;
},
async axiosUpdate(){
const res= await this.$axios.put('test/111');
this.textUpdate=res.data;
},
async axiosDelete(){
const res= await this.$axios.delete('test/11');
this.textDelete=res.data;
}
}
}
</script>
3)test.js (백엔드 서버 : Node.js )
node.js로 CORS 방식 허용하기로
# http, express, cors 모듈 설치 후
npm install http express cors
test.js
const express = require('express');
require('express-async-errors');
const app = express();
const cors = require('cors');
app.use(cors());
//인증 처리 미들웨어
app.use(require('../middlewares/verifyToken'));
//const router = express.Router();
/* GET users listing. */
//router.get('/', function (req, res, next) {
//res.send('respond with a resource test');
//res.render("test", { student_id: 'tes1t' });
//});
app.post('/', async (req, res, next) => {
res.send("post ok : ");
});
app.get('/', (req, res, next) => {
res.send("get ok : " + req.params.id);
});
app.get('/:id', (req, res, next) => {
res.send("get ok - " + req.params.id);
});
app.put('/:id', (req, res, next) => {
res.send("put ok - " + req.params.id);
});
app.delete('/:id', (req, res, next) => {
res.send("delete ok - " + req.params.id);
});
//에러 처리 미들웨어
app.use(require('../middlewares/error'));
module.exports = app;
middlewares/verifyToken.js
module.exports=(req, res, next) => {
//console.log(JSON.stringify(req.headers))
console.log(req.headers);
console.log("인증 처리hear");
next();
};















댓글 ( 5)
댓글 남기기