vue中请求接口怎么封装公共地址_vue请求接口的封装
import api from './api';
import request from'./request';//獲取url上的rest參數(shù),返回參數(shù)列表 /{userId}/{roleId} => ['userId', 'roleId']
functiongetUrlParams(url) {return (url.match(/\{(\w+)\}/g) || []).map(param => /\{(\w+)\}/.exec(param)[1]);
}/** 創(chuàng)建一個(gè)請(qǐng)求函數(shù)
* 閉包,用于保存isProcessing變量
* 通過(guò)isProcessing控制接口不發(fā)生多次請(qǐng)求
**/
function createRequest(url, method = 'post') {
let isProcessing= false;
let timeOut= true;
const urlParams= getUrlParams(url); //獲取url上的rest參數(shù) 用于后續(xù)處理
//encryResquest 控制參數(shù)是否集體加密
//encryResponse 控制回參是否需要解密
return function (data, callback, config = {}, force = false) {//force 傳true跳過(guò)不同時(shí)多次請(qǐng)求限制
if (isProcessing && !force) return;
isProcessing= true;
let headerIn={
headers:{}
}if(sessionStorage.getItem("userTk"))headerIn.headers.Authorization = sessionStorage.getItem("userTk")
config=Object.assign(headerIn,config)
console.info("工程頭部",config)
let option=Object.assign({
url: url,
method: method,
}, config);//處理rest參數(shù), 把url上的{param}替換,并且把data對(duì)應(yīng)的key刪掉,防止引起可能的400錯(cuò)誤
urlParams.forEach(param =>{
option.url=option.url.replace(`{${param}}`, data[param]);
Reflect.deleteProperty(data, param);
});if (method === 'post') option.data =data;if (method === 'get') option.params =data;
request(option)
.then(res=>{
console.info("終極參數(shù)",res)
isProcessing= false;var goLogin = false;if(res.data.statusCode === "403"){
goLogin= true}else{var resList = res.data.toString().split('statusCode=')if(resList.length>1){var tiplist = resList[1].split(', ')var code = tiplist.length>0?tiplist[0]:''
if(code === '403'){
goLogin= true}
}
}if(goLogin){
alert("超時(shí)登錄,請(qǐng)重新登錄")
setTimeout(()=>{
location.href="/"},500)return;
}
callback(res.data,res.headers);
})
.catch(err =>{
isProcessing= false;if(err.response) {
const code=err.response.status;if(timeOut && code === 401){
timeOut= falsealert("超時(shí)登錄,請(qǐng)重新登錄")
setTimeout(()=>{
timeOut= truelocation.href="/"},500)return;
}
callback({statusCode: code, message: `服務(wù)出錯(cuò)了:${code},請(qǐng)稍后再試!`});
}else{
console.info(err)
console.error('回調(diào)中代碼邏輯出問(wèn)題了!', err);
}
});
}
}
let service={};
Object.keys(api).forEach(module=>{
let moduleReq= service[module] ={};
Object.keys(api[module]).forEach(name=>{
const apiConfig=api[module][name];//獲取url 是一個(gè)string時(shí)默認(rèn)使用post請(qǐng)求,是一個(gè)對(duì)象時(shí),通過(guò)對(duì)象的method來(lái)調(diào)用對(duì)象的url
if (typeof apiConfig === 'string') {
moduleReq[name]=createRequest(apiConfig);
}else{
moduleReq[name]=createRequest(apiConfig.url, apiConfig.method);
}
});
});
exportdefault service;
總結(jié)
以上是生活随笔為你收集整理的vue中请求接口怎么封装公共地址_vue请求接口的封装的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
                            
                        - 上一篇: 科大讯飞智能办公本X3发布 售价4999
 - 下一篇: 迪士尼新片《小美人鱼》今日上线国内视频平