在src目录下新增一个目录utils,并新增一个js文件http.js,用以实现axios的封装
编辑http.js,首先导入axios
import axios from 'axios'
定义Http Request公共信息,用以添加授权等
axios.interceptors.request.use(
config => {
let token = 'lanol'
config.headers.token = token;
if (config.method == 'get') {
config.params.token = token
}
if (config.method == 'post') {
config.data.token = token
}
return config;
},
error => {
return Promise.reject(err);
}
)
封装Get方法
export function get(uri, params = {}) {
return new Promise((resolve, reject) => {
axios.get(uri, {
params: params
})
.then(response => {
resolve(response.data)
})
.catch(err => {
reject(err)
})
})
}
封装POST方法
export function post(uri, data = {}) {
return new Promise((resolve, reject) => {
axios.get(uri, {
params: params
})
.then(response => {
resolve(response.data)
})
.catch(err => {
reject(err)
})
})
}
封装patch请求
export function patch(url, data = {}) {
return new Promise((resolve, reject) => {
axios.patch(url, data)
.then(response => {
resolve(response.data);
}, err => {
reject(err)
})
})
}
封装PUT请求
export function put(url, data = {}) {
return new Promise((resolve, reject) => {
axios.put(url, data)
.then(response => {
resolve(response.data);
}, err => {
reject(err)
})
})
}
实现跨域
const downloadUrl = url => {
let iframe = document.createElement('iframe')
iframe.style.display = 'none'
iframe.src = url
iframe.onload = function() {
document.body.removeChild(iframe)
}
document.body.appendChild(iframe)
}
import axios from 'axios'
import {get,post} from '@/utils/http.js'
Vue.prototype.$ajax = axios
Vue.prototype.$post = post
Vue.prototype.$get = get
<template>
<div id="app">
{{Lan}}
</div>
</template>
<script>
import axios from '@/utils/http.js'
export default {
name: 'app',
components: {
},
data() {
return {
Lan: ''
}
},
mounted() {
this.$get('https://v1.hitokoto.cn').then((response)=>{
this.Lan = response.hitokoto
console.log(response);
})
}
}
</script>
<style>
#app {
font-family: 'Avenir', Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>