主要使用以下文件
config.js:ajax 請求配置核心文件
loading.js:element-ui 請求加載動畫
index.js:二次封裝 config.js 請求并導(dǎo)出該方法禾嫉,配置請求攔截器昌执、響應(yīng)攔截器
index.vue:調(diào)用 ajax 的示例頁面
注意:推薦在 api 目錄統(tǒng)一管理所有接口妙同,如果遇到報錯請調(diào)整正確引用路徑
config.js
import loading from './loading.js'; // 加載動畫類
const animation = false; // 接口加載動畫
const intTimer = 10; // 接口請求超時時間(秒)
class Config {
constructor(data) {
this.method = data.method;
this.url = data.url;
this.param = data.param || {};
this.header = data.header || {};
this.interceptors = data.interceptors;
this.response = data.response;
return this.filter();
}
// 創(chuàng)建XHR對象
createXHR() {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
return new XMLHttpRequest();
} else {
// code for IE6, IE5
return new ActiveXObject('Microsoft.XMLHTTP');
}
}
// HTTP請求
xhrRequest(header, method, url, param, async, interceptors, response) {
return new Promise(resolve => {
var xhr = this.createXHR();
if (animation == true) {
loading.requestStart(); // 執(zhí)行動畫
}
// 請求攔截
if (interceptors({ header, method, url: this.url, param: this.param, async })) {
xhr.open(method, url, async);
xhr.timeout = 1000 * intTimer; //設(shè)置xhr請求的超時時間
Object.keys(header).map(key => {
xhr.setRequestHeader(key, header[key]);
});
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; application/json; charset=utf-8');
xhr.send(param);
xhr.onreadystatechange = () => {
if (xhr.readyState == 4 && xhr.status == 200) {
loading.requestEnd(); // 結(jié)束動畫
try {
let data = JSON.parse(xhr.responseText);
resolve(response(data, { header, method, url: this.url, param: this.param, async }));
} catch (error) {
console.log('接口返回沒有任何信息!');
resolve(false);
}
} else {
return 'request is unsucessful ' + xhr.status;
}
};
} else {
console.error('request interceptor', '請求未發(fā)出, 請求攔截器已生效!');
}
// 請求超時方法
xhr.ontimeout = function(e) {
console.log('接口請求超時!');
loading.requestEnd(); // 結(jié)束動畫
};
// 請求錯誤方法
xhr.onerror = function(e) {
console.log('接口請求失敗');
loading.requestEnd(); // 結(jié)束動畫
};
});
}
// 參數(shù)轉(zhuǎn)換
convParams(param) {
let mark = '?';
let hasMark = this.url.indexOf(mark) > 0; // 是否包含特殊字符
if (hasMark) {
mark = '&';
}
let newParams = '';
let i = 0;
for (let key in param) {
if (i > 0) {
newParams += `&${key}=${param[key]}`;
} else {
newParams += `${mark}${key}=${param[key]}`;
}
i++;
}
return newParams;
}
// 數(shù)據(jù)GET杈湾、POST請求處理
filter() {
let obj = {
header: this.header,
method: this.method,
url: this.url,
param: {},
async: true,
interceptors: this.interceptors,
response: this.response
};
// 接口名稱拼接位置:(1、url) (2费变、param)
let newParams = this.convParams(this.param);
if (this.method == 'GET') {
obj.url += newParams;
} else {
newParams = newParams.replace('?', '');
obj.param = newParams;
}
return this.xhrRequest(obj.header, obj.method, obj.url, obj.param, obj.async, obj.interceptors, obj.response);
}
}
export default Config;
loading.js
import { Loading } from 'element-ui';
class animation {
constructor() {
this.needLoadingRequestCount = 0;
this.loading
}
/**
* 動畫開始
*/
requestStart() {
if (this.needLoadingRequestCount === 0) {
this.loading = Loading.service({
lock: true,
text: 'loading...',
background: 'rgba(0, 0, 0, 0.7)'
});
}
this.needLoadingRequestCount++;
}
/**
* 動畫結(jié)束
*/
requestEnd() {
if (this.needLoadingRequestCount <= 0) return;
this.needLoadingRequestCount--;
if (this.needLoadingRequestCount === 0) {
this.loading.close();
}
}
}
export default new animation()
index.js
import Config from './config.js';
/**
* 接口請求方法
* @func request
* @param {Object} method 請求方式: 僅支持GET摧扇、POST
* @param {String} url 請求地址
* @param {Object} param 請求參數(shù)
*/
let request = option => {
// 配置默認(rèn)請求參數(shù)
return new Config({
header: {
Authorization: 'APPCODE edc39cc1dc5f4c139498322115b99e51'
},
method: option.method,
url: option.url,
param: option.param,
interceptors: interceptors,
response: response
});
};
/**
* 請求攔截器
* @func interceptors
*/
let interceptors = config => {
return true;
};
/**
* 響應(yīng)攔截器
* @func response
*/
let response = (data, config) => {
let res;
// 處理返回格式
if (data.res) {
res = data.res;
} else if (data.data) {
res = data.data;
} else {
res = data;
}
return res;
};
export default request;
index.vue
<script>
import request from './index.js';
export default {
mounted() {
new request({
method: 'GET', // 請求方式: GET、POST
url: 'http://10.10.10.10/xxx/xxx', // 請求地址
param: {} // 請求參數(shù)
}).then(res => {
console.log('res', res);
});
}
};
</script>
文章的內(nèi)容/靈感都從下方內(nèi)容中借鑒
【持續(xù)維護(hù)/更新 500+前端面試題/筆記】https://github.com/noxussj/Interview-Questions/issues
【大數(shù)據(jù)可視化圖表插件】https://www.npmjs.com/package/ns-echarts
【利用 THREE.JS 實(shí)現(xiàn) 3D 城市建模(珠海市)】https://3d.noxussj.top/