当前位置:网站首页>Encapsulating a uni network request (uni. Request)
Encapsulating a uni network request (uni. Request)
2022-04-22 06:44:00 【Zhou zhouchi】
In the previous project , After the conclusion, I wrote a report based on uni Of api(uni.request) Encapsulated network request , Work well , Take a note
api centralized management , Easy to view and maintain
apiUrl/apiUrl.js
// API Do not modify
const apiUrl = {
home: {
xxxxxx: 'xxxxxx/xxxxxx/xxxxxx', // Get a list of stores
},
Collage: {
}
};
export default apiUrl;
Splice domain names
request/appOnlaunch.js
import apiUrl from '../ApiUrl/apiUrl.js';
import {
appUrl
} from '@/config/config.js'; // Import domain prefix
let siteInfo = {
'version': '1.0.0',
'apiroot': appUrl,
};
const spliceUrl = (ip, apiUrl) => {
let newUrl = {
};
for (let k in apiUrl) {
let newOb = {
[k]: {
}
};
for (let i in apiUrl[k]) {
newOb[k][i] = `${
ip}${
apiUrl[k][i]}`;
}
newUrl[k] = newOb[k];
}
return newUrl;
};
export default spliceUrl(siteInfo.apiroot, apiUrl);
encapsulation uni.request()
import $store from '../store/index.js';
import $user from '../common/user.js';
import {
token
} from '@/config/AppParameter.js';
const request = async function(args) {
if (args.loading) uni.showLoading({
title: ' Loading ',
mask: true
});
const headre = {
'content-Type': 'application/json',
'token': $store.getters['user/ReturnAccessToken'] || uni.getStorageSync(token) || ''
};
const [error, response] = await uni.request({
url: args.url,
method: args.method || 'Get',
data: args.data,
header: headre
});
if (error) {
let msg = {
code: 400,
msg: error.errMsg,
data: error
};
if (args.loading) {
uni.hideLoading();
uni.stopPullDownRefresh();
}
alertError(msg);
return Promise.reject(msg);
} else {
if (args.loading) {
return distinguishStatusCode(response, args.loading);
} else {
return distinguishStatusCode(response);
}
}
};
const reloadPage = function() {
let pages = getCurrentPages();
let page = pages[pages.length - 1];
let options = page.options || {
};
let route = page.route || '';
if (route.indexOf('/') !== 0) {
route = '/' + route;
}
let query = '';
for (let k in options) {
query = query + `${
k}=${
options[k]}&`;
}
uni.redirectTo({
url: route + (query ? `?${
query}` : ''),
});
};
const alertError = function(error) {
uni.showModal({
title: ' Network error ',
content: ' The Internet has wandered , Please refresh and try again ~',
cancelText: ' Copy error ',
confirmText: ' Refresh the page ',
success: (e) => {
if (e.cancel) {
let data = `code: ${
error.code}, \r\nmsg: ${
error.msg}, \r\ndetail: ` +
(error.data ? (typeof error.data === 'string' ? error.data : JSON.stringify(error
.data)) : null);
uniCopy({
data: data
});
}
if (e.confirm) {
reloadPage();
}
},
});
};
const distinguishDataCode = function(response, loading) {
// Status code defined in the background
if (response.data) {
let {
msg,
code,
} = response.data;
if (code == 200 || code == 201) {
return Promise.resolve(response.data);
} else if (code == 304) {
uni.hideLoading();
uni.stopPullDownRefresh();
uni.showToast({
title: msg,
icon: 'none',
duration: 4000,
});
return Promise.resolve(response.data);
} else if (code == 411) {
//token invalid , Login information is invalid
try {
uni.hideLoading();
uni.stopPullDownRefresh();
uni.clearStorageSync();
} catch (e) {
}
uni.showToast({
title: msg,
icon: 'none',
duration: 3000
});
$user.Silentlogin().then(res => {
// Silent login
uni.switchTab({
url: '/pages/pages/Home.vue'
});
}).catch(() => {
uni.showToast({
title: ' Login failed , Please re-enter the applet ',
icon: 'none',
duration: 4000
});
return Promise.reject({
code: 411,
msg: ' Login failed , Please re verify your login information ',
data: response,
});
});
} else {
uni.hideLoading();
uni.stopPullDownRefresh();
alertError({
code: code,
msg: msg,
data: response.data.error || (response.data.data || msg),
});
return Promise.reject(msg);
}
} else {
uni.hideLoading();
uni.stopPullDownRefresh();
return Promise.reject({
code: 200,
msg: ' The data doesn't exist ',
data: response,
});
}
};
const distinguishStatusCode = function(response, loading) {
let msg = {
code: 500,
msg: ' Server internal error ',
data: response,
};
switch (response.statusCode) {
case 200:
return distinguishDataCode(response, loading);
case 404:
msg = {
code: 404,
msg: ' Resource not available ',
data: response,
};
break;
case 500:
msg = {
code: 500,
msg: ' Server internal error ',
data: response,
};
break;
case 503:
msg = {
code: 503,
msg: ' Service not available ',
data: response,
};
break;
case 504:
msg = {
code: 504,
msg: ' gateway timeout ',
data: response,
};
break;
case 400:
msg = {
code: 400,
msg: ' The server does not understand the syntax of the request ',
data: response,
};
break;
case 403:
msg = {
code: 403,
msg: ' Server rejects request ',
data: response,
};
break;
case 405:
msg = {
code: 405,
msg: ' Method disable ',
data: response,
};
break;
case 406:
msg = {
code: 406,
msg: ' Unable to respond to the requested page using the requested content attribute ',
data: response,
};
break;
case 407:
msg = {
code: 407,
msg: ' Proxy authorization required ',
data: response,
};
break;
case 408:
msg = {
code: 408,
msg: ' request timeout ',
data: response,
};
break;
case 409:
msg = {
code: 409,
msg: ' Conflict ',
data: response,
};
break;
case 410:
msg = {
code: 410,
msg: ' deleted ',
data: response,
};
break;
case 411:
msg = {
code: 411,
msg: ' Effective length required ',
data: response,
};
break;
case 412:
msg = {
code: 412,
msg: ' The server does not meet one of the prerequisites set by the requester in the request ',
data: response,
};
break;
case 413:
msg = {
code: 413,
msg: ' Request entity too large ',
data: response,
};
break;
case 414:
msg = {
code: 414,
msg: ' Intercede URI Too long ',
data: response,
};
break;
case 415:
msg = {
code: 415,
msg: ' Unsupported media types ',
data: response,
};
break;
case 416:
msg = {
code: 416,
msg: ' The request scope does not meet the requirements ',
data: response,
};
break;
case 417:
msg = {
code: 417,
msg: ' Not meeting expectations ',
data: response,
};
break;
default:
break;
}
uni.hideLoading();
uni.stopPullDownRefresh();
alertError(msg);
return Promise.reject(msg);
};
const uniCopy = function({
// Copy error
data,
success,
error
}) {
// #ifndef H5
uni.setClipboardData({
data: data,
success() {
success && success();
}
});
// #endif
// #ifdef H5
if (!document.queryCommandSupported('copy')) {
// In order to be compatible with some browsers queryCommandSupported The judgment of the
// Replication is not supported
}
let textarea = document.createElement('textarea');
textarea.value = data;
textarea.readOnly = 'readOnly';
document.body.appendChild(textarea);
textarea.select(); // Select object
textarea.setSelectionRange(0, data.length); // The core
let result = document.execCommand('copy'); // Execute browser copy command
if (result) {
success && success();
} else {
}
textarea.remove();
// #endif
};
export default request;
stay man.js Register in and mount to vue On the prototype chain
import Api from '@/request/appOnlaunch.js';
Vue.prototype.$api = Api; // Interface route
import Request from '@/request/request.js';
Vue.prototype.$request = Request; // request
Usage mode :
.then
getBanner() {
this.$request({
url: this.$api.home.banner,
data: {
type: 2
},
method: 'POST',
loading: true,
}).then(response => {
console.log(' Requested data ', response);
});
},
async/await
async getBanner() {
const e = await this.$request({
url: this.$api.home.banner,
data: {
type: 2
},
method: 'POST'
})
let {
status,
data,
msg,
} = e;
if (status != 200) console.log(" The status code is not 200")
else {
console.log(" Requested data ", data)
}
},
promises.all
const promises = [this.$api.mineday.craftsman, this.$api.mineday.serviceType].map((item, index) => {
let data = {
}
if (index == 0) {
data = {
child_store_id: this.StoreDataList.id
}
}
return this.$request({
url: item,
method: "GET",
data: data
})
})
Promise.all(promises).then(values => {
console.log(" Requested data set ", values)
})
One is based on uni Native api(uni.request) Encapsulated network request
版权声明
本文为[Zhou zhouchi]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204220557472409.html
边栏推荐
- Pixel系列无痛升级
- Mapping of oid and relfilenode in PostgreSQL
- 在微信小程序中打开的页面不能超过10个,达到10个页面后,就不能再打开新的页面
- 创新实训(十)
- Escort · the future 𞓜 digital risk control summit of digital America 2022 officially set off
- uniapp自定义底部导航栏h5有效果小程序无效的解决方案
- Redis的安装启动,菜鸟使用(windows)
- Using pgbackrest parallel archiving to solve wal stacking problem
- 剑指offer:数据流中的中位数(优先队列 大顶堆小顶堆 leetcode 295)
- ArcMAP TIN与栅格DEM的坡度坡向对比分析
猜你喜欢
随机推荐
The difference between equalsignorecase() and equals()
pixel手机救砖教程
利用win自带功能让处于同一局域网的两个电脑之间互传文件(速度和本地磁盘间互传相同)
小程序自定义原生底部导航
Waterfall layout JS positioning
使用@Autowired出现Field injection is not recommended
如何设置窗口函数中窗口的大小
uniapp web-view示例(微信小程序)
List<Map>复制:浅拷贝与深拷贝
Shumei technology was honored as the top 20 of the new enterprise service track of "real 100 innovators" in the interface news
每日一题——寻找小于目标数的最大单调递增数
ArcGIS 观景点视域分析
js判断PC端或移动端
PostgreSQL 13.3, 12.7, 11.12, 10.17 and 9.6.22 have been released!
API centralized management
Iframe child parent pass parameter
ArcMAP TIN与栅格DEM的坡度坡向对比分析
MySQL——一条语句的执行流程和原理
MYSQL 使用OR查询SQL执行很慢
从零开始学安卓(kotlin)五——UI









