// 配置API接口地址与服务器静态文件地址
var root = 'http://127.0.0.1:3000/';
// 引用axios
var axios = require('axios')
var qs = require('qs')
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8'
//全局封装错误处理函数
axios.interceptors.request.use(
config => {
config.headers = {
'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
};
// 在post请求发送出去之前,对其进行编码
if (config.method === 'post') {
config.data = qs.stringify(config.data);
}
return config;
},
err => {
return Promise.reject(err);
});
// http response 拦截器
axios.interceptors.response.use(
response => {
return response;
},
error => {
if (error.response) {
console.log("请求错误", error.response.status);
switch (error.response.status) {
case 401:
// store.dispatch('logout');
console.log("401");
break;
case 404:
console.log('接口不存在');
break;
case 500:
console.log('服务器错误');
}
}
return Promise.reject(error);// 返回接口返回的错误信息
});
function getdata(method, url, params, success, failure) {
axios({
method: method,
url: url,
data: method === 'POST' || method === 'PUT' ? params : null,
params: method === 'GET' || method === 'DELETE' ? params : null,
baseURL: root,
withCredentials: true, //跨域请求凭证验证。
timeout: 30000
})
.then(function (res) {
success(res.data);
})
.catch(function (err) {
let res = err.response
if (err) {
console.log('api error, HTTP CODE: ' + res.status)
failure(err.response.statusText)
return
}
})
}
// 返回在vue模板中的调用接口
export default {
get: function (url, params, success, failure) {
return getdata('GET', url, params, success, failure)
},
post: function (url, params, success, failure) {
return getdata('POST', url, params, success, failure)
},
put: function (url, params, success, failure) {
return getdata('PUT', url, params, success, failure)
},
delete: function (url, params, success, failure) {
return getdata('DELETE', url, params, success, failure)
},
root: root
}
post请求需要qs模块进行编码,不然后台接收到数据还需要处理,编码前后后台接收到的数据格式如下(后台语言为nodejs)
封装完成后需要在main.js进行引用。引用的代码如下。
import api from './api/index' //封装axios方法js的地址
Vue.prototype.$api = api //装载到vue实例上方便调用
调用方法
this.$api.post(
"post",
{id:1,name:"142adasdlkjasd"},
response => {
console.log(response);
},
err=> {
console.log(err);
}
);
}