vue对axios的封装

//安装后引入
import axios from “axios”;
import qs from “qs”

const debug = process.env.NODE_ENV === “development”; //区分开发环境与生产环境

function apiUnit (url, params, method=“post”) {
return new Promise ((resolve, reject) => {
let option = {
method: method,
url: url
};
if (method === “post”) {
option.data = qs.stringify(params);
} else {
option.params = params;
}
axios(option).then((res) => {
resolve(res.data)
}).catch((e) => {
reject(e);
});
})
}

//使用例子:
function userLogin (obj) {
let url = debug ? “/Mobile/Login” : createFetchUrl(HostName,"/Mobile/Login");
let params = Object.assign({}, obj);

return new Promise((resolve, reject) => {
apiUnit (url, params, “post”).then((res) => {
if (res.code !== 200) {
reject(createErrorObject(res.msg));
} else {
resolve(res);
}
}).catch((e) => {
reject(e);
});
});
}

HostName是生产环境的站点
/Mobile/Login为接口名称
在接口调用时用userLogin

你可能感兴趣的:(vue对axios的封装)