1.前言:之前是我負責這個項目的搭建,及打包上線,整個項目都是我一個人來做,所以接口寫的遍地都是,造成了瀏覽起來很難受,不便於維護 ,所以就打算封裝一下axios 創建一個apis 的js文件來集中管理接口,走着!
首先考慮的是通過promise來封裝axios,使代碼看起來更清晰明瞭
2.1 項目中引入axios
使用npm安裝
$ npm install axios
main.js引入axios模塊
import axios from 'axios'
Vue.prototype.$http = axios
3.promise封裝axios
項目新建一個utils.js文件
/***
*
* promise 二次封裝請求
*/
import axios from "axios";
// 一些請求的基本配置
const service = axios.create({
baseURL: "************", // 接口的域名地址
headers: {
"Content-Type": "application/x-www-form-urlencoded;charset=utf-8"
}
});
// 輸出方法
export default function request(url, data = {},method="post") { // 如果此處的method爲get 則需要傳入get,默認爲post
return new Promise((resolve, reject) => {
const options = {
url,
method
};
if (method.toLowerCase() === "get") {
options.params = data; //如果爲get傳參爲params
} else {
options.data = data; // post等 傳數據爲data
}
service(options)
.then(res => {
console.log("返回數據", res);
resolve(res.data); //返回數據
})
.catch(error => {
reject();
console.error(error); //異常捕獲
});
});
}
4.再apis文件引入封裝好的utils.js文件
import request from "../utils/utils" // 引入utils.js
將所有接口集中再api對象裏面管理
const api = {
// 獲取驗證碼
get_code(data) {
return request("api", data,'get'); // 修改請求方式
},
// 登錄
login(data) {
return request("api",data);
}
}
將api暴露出去,供頁面組件引用
export default api;
apis.js文件完整代碼
/**
*
* 引入封裝好的request
* api 接口庫
*/
import request from "../utils/utils";
const api = {
// 獲取驗證碼
get_code(data) {
return request("api", data,'get');
},
// 登錄
login(data) {
return request("api",data);
}
};
export default api;
5.頁面引用
let data = { telephone: this.data.inputName } //需要上傳的參數
發起請求
//請求參數
API.get_code(data)
.then(res => {
this.$message({showClose: true, message: res.msg,type: "success" });
})
.catch(err => {
//請求失敗
});
6.請求成功
嘿嘿結束!!!