axios 封装

≯℡__Kan透↙ 提交于 2020-02-26 00:37:31

const baseURL = ‘http://192.168.7.22:9010’;
axios.defaults.timeout = 10000;

function apiAxios(method, url, params){
let httpDefault = {
method,
baseURL,
url,
headers:{
‘Content-Type’: ‘application/json’,
‘userName’:store.state.user.userName,
‘userId’:store.state.user.userId
},
// params 是即将与请求一起发送的 URL 参数
// data 是作为请求主体被发送的数据
params: method === ‘GET’ || method === ‘DELETE’ ? params : null,
data: method === ‘POST’ || method === ‘PUT’ ? JSON.stringify(params) : null,
timeout: 10000
}
return new Promise((resolve, reject) => {
axios(httpDefault)
// 此处的.then属于axios
.then((res) => {
resolve(res)
}).catch((response) => {
reject(response)
})
})
}
// 输出函数getAxios、postAxios、putAxios、delectAxios,供其他文件调用-----------------------------
// Vue.js的插件应当有一个公开方法 install。这个方法的第一个参数是 Vue 构造器,第二个参数是一个可选的选项对象。

/export default {
install: function (Vue) {
Vue.prototype.getAxios = (url, params) => apiAxios(‘GET’, url, params)
Vue.prototype.postAxios = (url, params) => apiAxios(‘POST’, url, params)
Vue.prototype.putAxios = (url, params) => apiAxios(‘PUT’, url, params)
Vue.prototype.delectAxios = (url, params) => apiAxios(‘DELECT’, url, params)
}
}
/
export default {
get : (url, params) => apiAxios(‘GET’, url, params),
post : (url, params) => apiAxios(‘POST’, url, params),
put :(url, params) => apiAxios(‘PUT’, url, params),
DELETE : (url, params) => apiAxios(‘DELETE’, url, params)
}

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!