当前位置:网站首页>封装uni网络请求(uni.request)
封装uni网络请求(uni.request)
2022-04-22 05:59:00 【周周池】
在前面的项目中,总结后写了一个基于uni的api(uni.request)封装的网络请求,比较好用,做个笔记
api集中管理,利于查看和维护
apiUrl/apiUrl.js
// API 请勿修改
const apiUrl = {
home: {
xxxxxx: 'xxxxxx/xxxxxx/xxxxxx', //获取店铺列表
},
Collage: {
}
};
export default apiUrl;
拼接域名
request/appOnlaunch.js
import apiUrl from '../ApiUrl/apiUrl.js';
import {
appUrl
} from '@/config/config.js'; //导入域名前缀
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);
封装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: '加载中',
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: '网络错误',
content: '网络开了小差,请刷新重试下哦~',
cancelText: '复制错误',
confirmText: '刷新页面',
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) {
//后台定义的状态码
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失效,登录信息失效
try {
uni.hideLoading();
uni.stopPullDownRefresh();
uni.clearStorageSync();
} catch (e) {
}
uni.showToast({
title: msg,
icon: 'none',
duration: 3000
});
$user.Silentlogin().then(res => {
// 静默登录
uni.switchTab({
url: '/pages/pages/Home.vue'
});
}).catch(() => {
uni.showToast({
title: '登录失败,请重新进入小程序',
icon: 'none',
duration: 4000
});
return Promise.reject({
code: 411,
msg: '登录失败,请重新验证登录信息',
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: '数据不存在',
data: response,
});
}
};
const distinguishStatusCode = function(response, loading) {
let msg = {
code: 500,
msg: '服务器内部错误',
data: response,
};
switch (response.statusCode) {
case 200:
return distinguishDataCode(response, loading);
case 404:
msg = {
code: 404,
msg: '资源获取不到',
data: response,
};
break;
case 500:
msg = {
code: 500,
msg: '服务器内部错误',
data: response,
};
break;
case 503:
msg = {
code: 503,
msg: '服务不可用',
data: response,
};
break;
case 504:
msg = {
code: 504,
msg: '网关超时',
data: response,
};
break;
case 400:
msg = {
code: 400,
msg: '服务器不理解请求的语法',
data: response,
};
break;
case 403:
msg = {
code: 403,
msg: '服务器拒绝请求',
data: response,
};
break;
case 405:
msg = {
code: 405,
msg: '方法禁用',
data: response,
};
break;
case 406:
msg = {
code: 406,
msg: '无法使用请求的内容特性响应请求的网页',
data: response,
};
break;
case 407:
msg = {
code: 407,
msg: '需要代理授权',
data: response,
};
break;
case 408:
msg = {
code: 408,
msg: '请求超时',
data: response,
};
break;
case 409:
msg = {
code: 409,
msg: '冲突',
data: response,
};
break;
case 410:
msg = {
code: 410,
msg: '已删除',
data: response,
};
break;
case 411:
msg = {
code: 411,
msg: '需要有效长度',
data: response,
};
break;
case 412:
msg = {
code: 412,
msg: '服务器未满足请求者在请求中设置的其中一个前提条件',
data: response,
};
break;
case 413:
msg = {
code: 413,
msg: '请求实体过大',
data: response,
};
break;
case 414:
msg = {
code: 414,
msg: '求情URI过长',
data: response,
};
break;
case 415:
msg = {
code: 415,
msg: '不支持的媒体类型',
data: response,
};
break;
case 416:
msg = {
code: 416,
msg: '请求范围不符合要求',
data: response,
};
break;
case 417:
msg = {
code: 417,
msg: '未满足期望值',
data: response,
};
break;
default:
break;
}
uni.hideLoading();
uni.stopPullDownRefresh();
alertError(msg);
return Promise.reject(msg);
};
const uniCopy = function({
//复制错误
data,
success,
error
}) {
// #ifndef H5
uni.setClipboardData({
data: data,
success() {
success && success();
}
});
// #endif
// #ifdef H5
if (!document.queryCommandSupported('copy')) {
//为了兼容有些浏览器 queryCommandSupported 的判断
// 不支持复制
}
let textarea = document.createElement('textarea');
textarea.value = data;
textarea.readOnly = 'readOnly';
document.body.appendChild(textarea);
textarea.select(); // 选择对象
textarea.setSelectionRange(0, data.length); //核心
let result = document.execCommand('copy'); // 执行浏览器复制命令
if (result) {
success && success();
} else {
}
textarea.remove();
// #endif
};
export default request;
在man.js中注册并且挂载到vue的原型链上
import Api from '@/request/appOnlaunch.js';
Vue.prototype.$api = Api; // 接口 路径
import Request from '@/request/request.js';
Vue.prototype.$request = Request; //请求
使用方式:
.then
getBanner() {
this.$request({
url: this.$api.home.banner,
data: {
type: 2
},
method: 'POST',
loading: true,
}).then(response => {
console.log('请求到的数据', 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("状态码不为200")
else {
console.log("请求到的数据", 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("请求到的数据集合", values)
})
一个基于uni原生api(uni.request)封装的网络请求
版权声明
本文为[周周池]所创,转载请带上原文链接,感谢
https://blog.csdn.net/weixin_45444562/article/details/123204273
边栏推荐
- Uniapp custom bottom navigation bar H5 has an effective solution to invalid applet
- 创新实训(二)任务划分
- 小程序自定义原生底部导航
- 小程序蓝牙连接低功耗设备(BLE)记录
- Arduino UNO r3+LCD1602+DHT11
- 《信息系统项目管理师总结》第一章 项目整体管理
- JS get screen, browser, web page height and width
- webService接口编写并发布与webService接口的调用(二)
- MySQL在面试中经常被问到的经典问题。
- ArcMAP TIN与栅格DEM的坡度坡向对比分析
猜你喜欢

MySQL is a classic question often asked in an interview.

js引擎的循环机制:同步,异步,事件循环

Uniapp custom bottom navigation bar H5 has an effective solution to invalid applet

The minors protection solution of digital beauty technology is heavily launched, opening a new era of minors' network escort

APP更新

Mvcc transaction isolation in PostgreSQL

MySQL备忘录(供自己查询所用)

EXCEL 分列功能的使用

EXCEL 利用替换、分列、填充功能综合整理财务数据

小程序自定义原生底部导航
随机推荐
MySQL在面试中经常被问到的经典问题。
Shumei technology was honored as the "top 100 scientific and technological innovation of private enterprises in Beijing"
Pixel系列无痛升级
JS, JQ single line text scrolling up and down
You can't open more than 10 pages in wechat applet. After reaching 10 pages, you can't open a new page
条形码生成及解码、二维码生成及解码
《信息系统项目管理师总结》第一章 项目整体管理
如何设置窗口函数中窗口的大小
The installation of redis is started and used by rookies (Windows)
创新实训(四)进度
JS judge the PC end or mobile end
EXCEL 分列功能的使用
创新实训(四)前期准备—服务器
Pgbackrest practice
关于调试指纹时候遇到的其他问题
Using ltree to process hierarchical data in PostgreSQL
如何清除浮动?
js引擎的循环机制:同步,异步,事件循环
How can enterprise risk control build four systems to achieve overall prevention and control?
equalsIgnoreCase()和equals()的区别