配置
目录: src / network / request.js
I : 创建axios实例,配置baseURL,timeout,hander...
-- baseURL 统一IP地址
II: 配置请求时拦截
-- 比如校验config中的一些信息是否符合服务器的要求
-- 比如每次发送网络请求时,都希望在界面显示一个请求的图标(loading)
-- 某些网络请求(比如token),必须携带一些特殊的信息
III: 响应时拦截
-- 返回需要的数据...
-- 异常处理
IV:默认导出instance
import axios from 'axios'
const instance = axios.create({
//
baseURL: 'http://' + location.hostname + ':1234/vcancbs/',
timeout: 5000
})
instance.interceptors.request.use(config => {
//...
console.log(config)
return config
}, error => {
console.log(error)
})
instance.interceptors.response.use(response => {
// ...
console.log(response )
return response.data
}, error => {
console.log(error)
})
export default instance
封装
目录: src / network / api.js
在api.js文件中 import axios from './request'
顺便封装了get、post、delete、方便调用,如需使用其他自行添加
import axios from './request'
/*
get
@param {路径,参数对象}
*/
export const _get = (url, query) => {
return new Promise((resolve, reject) =>{
axios.get(url, {
params: query
})
.then(res => {
resolve(res.data);
})
.catch(err => {
reject(err.data)
})
})
}
/*
post
@param {路径,参数对象}
*/
export const _post = (url, query) => {
return new Promise((resolve, reject) => {
axios.post(url, query)
.then(res => {
resolve(res.data);
})
.catch(err => {
reject(err.data)
})
});
}
/*
delete
@param {路径,参数对象}
*/
export const _delete = (url, query) => {
return new Promise((resolve, reject) => {
axios.delete(url, query)
.then(res => {
resolve(res.data);
})
.catch(err => {
reject(err.data)
})
});
}
全局引入
目录:src / main.js
在main.js文件中 import { _get, _post, _delete} from './network/api',然后添加Vue全局属性$get、$post、$delete,Vue.prototype.xxx = arg
import Vue from 'vue'
import App from './App.vue'
import { _get, _post, _delete} from './network/api'
Vue.prototype.$get = _get
Vue.prototype.$post = _post
Vue.prototype.$delete = _delete
Vue.config.productionTip = false
new Vue({
render: h => h(App),
}).$mount('#app')
使用
使用 : const f = (url, param) => { this.$post(url, { ... }).then(res => { ... }).catch(err => { ... })}
getFun(){
this.$get('bingniter/getOrderInfo',{id:'bingniter-2020-10-24'}).then( response => {
console.log(response)
}, error => {
console.log(error)
})
}
postFun(){
this.$post('bingniter/getDataSource',{id:'bingniter-2020-10-24',name:'BingNiTer'}).then( response => {
console.log(response)
}, error => {
console.log(error)
})
}