請(qǐng)求框架config配置
config.js
// http 請(qǐng)求配置項(xiàng)
export default {
// 開發(fā)者服務(wù)器接口地址
url: "http://xxxxxxxxxxxxxxxxxxxxxx",
// 請(qǐng)求的參數(shù)
data: {},
// 設(shè)置請(qǐng)求的 header葵腹,header 中不能設(shè)置 Referer。
header: {
'token':uni.getStorageSync('token'),
'Content-Type':'application/x-www-form-urlencoded;charset=UTF-8'
},
// (需大寫)有效值:OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
method: "POST",
// json 如果設(shè)為json屿岂,會(huì)嘗試對(duì)返回的數(shù)據(jù)做一次 JSON.parse
dataType: "json",
// text 設(shè)置響應(yīng)的數(shù)據(jù)類型践宴。合法值:text、arraybuffer 1.7.0
responseType: "text",
// 收到開發(fā)者服務(wù)成功返回的回調(diào)函數(shù)
success() {},
// 接口調(diào)用失敗的回調(diào)函數(shù)
fail() {},
// 接口調(diào)用結(jié)束的回調(diào)函數(shù)(調(diào)用成功爷怀、失敗都會(huì)執(zhí)行)
complete() {},
}
未登錄前token取到是空阻肩,登錄后把后臺(tái)返回的token存儲(chǔ)到緩存,到下一個(gè)界面請(qǐng)求其他接口的時(shí)候霉撵,頭信息里面的token為空磺浙,并且本地緩存信息已有token洪囤,于是想到是請(qǐng)求頭里面的token并沒有更新,需要去更新一下就可以了撕氧。
interface.js
import _config from './config'; // 導(dǎo)入私有配置
export default function $http(options) {
console.log(_config.url , options.url)
options.url = _config.url + options.url;
return new Promise((resolve, reject) => {
// 進(jìn)行url字符串拼接
// 攔截請(qǐng)求
//第一次無token配置請(qǐng)求頭為空,在這邊更新下header里面的token
_config.header['token'] = uni.getStorageSync('token')
_config.complete = (response) => {
// request請(qǐng)求訪問成功
if (response.statusCode === 200) {
// 接口請(qǐng)求成功
resolve(response);
} else {
// 處理catch 請(qǐng)求瘤缩,不在本頁面之外處理,統(tǒng)一在這里處理
if(options.handle){
reject(response)
}else{
try {
Promise.reject(response).catch(err => {
// console.error(err);
_page_error(response.statusCode || response.errMsg);
});
} catch (e) {
console.log(e)
}
}
}
}
// 開始請(qǐng)求
uni.request(Object.assign({},_config, options));
})
}
index.js
import https from './interface'
/**
* 將所有接口統(tǒng)一起來便于維護(hù)
* 如果項(xiàng)目很大可以將 url 獨(dú)立成文件伦泥,接口分成不同的模塊
* handle [boolean] 如果需要自己處理 catch 請(qǐng)求 剥啤,傳入 true ,交給接口統(tǒng)一處理 不脯,請(qǐng)傳如 false或不傳
*/
// 單獨(dú)導(dǎo)出
//登錄
export const login = (data) => {
return https({
url: '/user/loginByUserName',
// method: 'GET', // 默認(rèn)POST
data,
// handle:true
})
}
// 默認(rèn)全部導(dǎo)出
export default {
login
}