將axios 請求封裝成公共方法,方面在項目中使用
1.首先在項目引入axios??
cnpm i?axios --save || npm i --save axios
2.在公共js引入axios

3.定義請求頭及過期時間

4.配置請求頭

5.請求地址的處理

actionName :接口名
baseURL:為請求的服務(wù)端地址
到此處請求的方法就完成了只需要在定義一個公共的方法去處理請求行參就可以
6.定義公共的方法,接收行參調(diào)用請求的方法
第一種封裝請求方式

reqUrl: 請求地址
reqMethod :請求方式
reqData :請求數(shù)據(jù)
callback:回調(diào)函數(shù)
dir :直接返回響應(yīng)數(shù)據(jù)(dir? 如果存在直接 返回后后臺返回的所有數(shù)據(jù),不存在則只返回data內(nèi)的數(shù)據(jù))

調(diào)用方式

第二種封裝方式


調(diào)用方式

源碼放在這里:
import axios from "axios";
let baseURL = 'http://www.baidu.con'
? ? // 創(chuàng)建請求體
const http = axios.create({
? ? timeout: 2000 * 300,
? ? headers: {
? ? ? ? "Content-Type": "application/json; charset=utf-8"
? ? }
});
http.__proto__ = axios;
/**
* 請求攔截
*/
http.interceptors.request.use(
? ? config => {
? ? ? ? config.headers.sn = "123456";
? ? ? ? return config;
? ? },
? ? error => {
? ? ? ? return Promise.reject(error);
? ? }
);
/**
* 響應(yīng)攔截
*/
http.interceptors.response.use(
? ? response => {
? ? ? ? if (response.data && response.data.code === 403) {
? ? ? ? ? ? // 401, 沒有權(quán)限
? ? ? ? } else if (response.data.code === 14003) {} else if (response.data.code && response.data.code !== 200) {
? ? ? ? ? ? let msg = response.data.msg;
? ? ? ? ? ? Toast(msg);
? ? ? ? }
? ? ? ? return response;
? ? },
? ? error => {
? ? ? ? return Promise.reject(error);
? ? }
);
/**
* 請求地址處理
*/
http.adornUrl = actionName => {
? ? ? ? return baseURL + actionName;
? ? }
? ? /**
? ? * 封裝ajax請求
? ? * 1.reqUrl、reqMethod為必填選項
? ? * 2.type存在時導(dǎo)出數(shù)據(jù)
? ? * @param {String}? reqUrl? ? ? ? ? ? ? ? ? 請求地址
? ? * @param {String}? reqMethod? ? ? ? ? ? ? ? 請求方式
? ? * @param {JSON}? ? reqData? ? ? ? ? ? ? ? ? 請求數(shù)據(jù)
? ? * @param {Function} callback? ? ? ? ? ? ? ? 回調(diào)函數(shù)
? ? * @param {Function} dir? ? ? ? ? ? ? ? ? ? ? 直接返回響應(yīng)數(shù)據(jù)
? ? */
? ? // 第一種方式
const myAjax = (reqUrl, reqMethod, reqData, callback, dir) => {
? ? http({
? ? ? ? ? ? url: http.adornUrl(reqUrl),
? ? ? ? ? ? method: reqMethod,
? ? ? ? ? ? data: reqData
? ? ? ? })
? ? ? ? .then(({ data }) => {
? ? ? ? ? ? if (dir) {
? ? ? ? ? ? ? ? callback(data);
? ? ? ? ? ? } else if (data && data.code == 200) {
? ? ? ? ? ? ? ? callback(data.data);
? ? ? ? ? ? }
? ? ? ? })
? ? ? ? .catch(({ data }) => {
? ? ? ? });
};
// 第二種方式
const myRequest = (reqUrl, reqMethod, reqData) => {
? ? return http.request({
? ? ? ? url: http.adornUrl(reqUrl),
? ? ? ? method: "post",
? ? ? ? data: reqData
? ? });
};
export default {
? ? myAjax,
? ? myRequest
};
/**
*
*? main.js 中如此引用
*?
*
* */
Vue.prototype.$myAjax = httpRequest.myAjax; // ajax請求方法
Vue.prototype.$myRequest = httpRequest.myRequest; // ajax請求方法
/**
*
* 第一種封裝方式調(diào)用請求
*
*
*
* */
this.$myAjax('/api', "post", { name: '參數(shù)' }, res => {
});
或
this.$myAjax('/api', "post", { name: '參數(shù)' }, res => {
}, 'res');
/**
*
* 第二種封裝方式調(diào)用請求
*
*
*
* */
const res2 = await this.$myRequest('/api', 'post', { name: '參數(shù)' })
const res0Data2 = res2.data