123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146 |
- // API配置信息
- import urls from '../common/config.js'
- /**
- * 构建完整请求URL
- * @param {Object} path
- */
- function buildUrl(path) {
- // 完整接口地址返回
- if (path.startsWith('http://') || path.startsWith('https://')) {
- return path;
- }
- return urls.api + path;
- }
- /**
- * 通用请求封装
- * @param {Object} path
- * @param {Object} data
- */
- function postData(path, data) {
- // 构建完整请求
- const url = buildUrl(path)
- return new Promise((resolve, reject) => {
- uni.request({
- url: url,
- data: data,
- method: "POST",
- header: {
- 'content-type': "application/json",
- 'token': uni.getStorageSync("token"),
- 'mac': uni.getStorageSync("mac") // APP.vue页面的mac地址
- },
- success: function(res) {
- // 错误500
- if (res.statusCode == 500) {
- uni.showToast({
- title: '糟糕,服务器开小差了~',
- icon: 'none',
- duration: 5000
- });
- return;
- }
- // 404
- if (res.statusCode == 404) {
- uni.showToast({
- title: '接口地址404,请联系管理员~',
- icon: 'none',
- duration: 5000
- });
- return;
- }
- // 成功才回调
- if (res.data.code === 0) {
- resolve(res.data.data);
- } else {
- // 后台错误信息
- uni.showToast({
- title: res.data.msg,
- icon: 'none',
- duration: 3000
- });
- if (res.data.code === 10010002) {
- // 跳转到登录
- uni.navigateTo({
- url: '/pages/login/login'
- });
- return;
- }
- reject(res.data)
- }
- },
- fail: function(e) {
- uni.showToast({
- title: '啊哦,与服务器失去连接了~',
- icon: 'none',
- duration: 10000
- });
- }
- });
- });
- }
- /**
- * 文件上传
- * @param {Object} url
- * @param {Object} file
- * @param {Object} data
- */
- function uploadData(path, file, formData) {
- // 构建完整请求地址
- let url = buildUrl(path)
-
-
- uni.showLoading({
- title: '正在上传...'
- })
-
- // 兼容chooseMedia
- const filePath = file.path || file.tempFilePath
-
- return new Promise((resolve, reject) => {
- uni.uploadFile({
- url: url,
- filePath: filePath,
- name: 'file',
- header: {
- 'token': uni.getStorageSync("token")
- },
- formData: formData,
- success: res => {
- let data = {}
- if (res.data) {
- data = JSON.parse(res.data)
- }
- resolve(data);
- uni.hideLoading()
- },
- fail: err => {
- reject()
- uni.hideLoading()
- }
- })
- });
- }
- module.exports = {
- post: postData,
- upload: uploadData
- };
|