uni-app接口统一处理request请求

用Promise就可以.then() 的方法进行回调
虽然有很多插件,但是这个是能看懂的
接下来是代码

前台

    • 新建一个request.js
    • 存token的本地存储类db.js
    • 封装get,post 到request.js
    • api.js
    • 调用
    • 附赠一个图片上传

新建一个request.js

import * as db from './db.js' //引入common
export const request = (params) => {
	uni.showLoading({
		title: "加载中"
	})
	return new Promise((resolve, reject) => {
		wx.request({
			...params,
			success(res) {
				var jsondata = res.data;
				if (jsondata.success) {
					resolve(jsondata);
				} else {
					showError(jsondata)
					resolve(jsondata);
					//应该是这个但它会抛异常统一处理后就不执行then事件了
					// reject(res.data)
				}
			},
			fail(err) {
				showError(err)
				reject(res.data)
			},
			complete() {
				uni.hideLoading();
			}
		})
	})
}
//错误处理
const showError = (error) => {
	var that = this
	if (error) {
		let data = error
		const token = db.get("userToken");
		console.log("------异常响应------", token)
		console.log("------异常响应------", error.status)
		switch (error.status) {
			case 403:
				uni.showToast({
					title: '拒绝访问',
					icon:'none',
					duration: 4000
				});
				break
			case 500:
				if (data.message == "Token失效,请重新登录") {
					uni.showModal({
						title: '登录已过期',
						content: '很抱歉,登录已过期,请重新登录',
						confirmText: '重新登录',
						success: function(res) {
							if (res.confirm) {
								db.del('userToken')
								//去我的页面登录
								uni.switchTab({
									url: '/pages/views/mine'
								});
							} else if (res.cancel) {
								console.log('用户点击取消');
							}
						}
					})
					// update-end- --- author:scott ------ date:20190225 ---- for:Token失效采用弹框模式,不直接跳转----
				}
				break
			case 404:
				uni.showToast({
					title: '很抱歉,资源未找到!',
					icon:'none',
					duration: 4000
				});
				break
			case 504:
				uni.showToast({
					title: '网络超时',
					icon:'none',
					duration: 2000
				});
				break
			case 502:
				uni.showToast({
					title: '服务器异常',
					icon:'none',
					duration: 2000
				});
				break
			case 401:
				uni.showToast({
					title: '未授权,请重新登录',
					icon:'none',
					duration: 4000
				});
				if (token=='') {
					setTimeout(() => {
						//去我的页面登录
						uni.switchTab({
							url: '/pages/views/mine'
						});
					}, 1500)
				}
				break
			default:
				uni.showToast({
					title: data.message,
					icon:'none',
					duration: 4000
				});
				break
		}
	}
	return null
};

存token的本地存储类db.js

//取值
function get(key,sync = true) {
    try {
		if(sync){
			return uni.getStorageSync(key);
		}else{
			let data = '';
			uni.getStorage({
				key:key,
				success: function (res) {
					data = res.data;
				}
			});
			return data;
		}
    } catch (e) {
        return false;
    }
}

//赋值
function set(key, value, sync = true) {
    try {
        if (sync) {
            return uni.setStorageSync(key, value);
        } else {
            uni.setStorage({
                key: key,
                data: value
            });
        }
    } catch (e) {

    }
}

//移除
function del(key, sync = true){
    try {
        if (sync) {
            return uni.removeStorageSync(key);
        } else {
            uni.removeStorage({
                key: key
            });
        }
    } catch (e) {
        return false;
    }
}

//清空
function clear(sync = true){
    try {
        if (sync) {
            return uni.clearStorageSync();
        } else {
            uni.clearStorage();
        }
    } catch (e) {
        return false;
    }
}

export {
    get,
    set,
    del,
    clear
}

封装get,post 到request.js


import * as db from './db.js'
//后台路径
const apiBaseUrl = ''
import {request} from '@/config/request.js'
const post = (method, data) => {
	uni.showLoading({
		title: '加载中'
	});
	var header={
			'Accept': 'application/json',
			'Content-Type': 'application/json',
			// 'Content-Type': 'application/x-www-form-urlencoded', //自定义请求头信息
		}
	header=setHeader(header);
	return request({
		url: apiBaseUrl + '/web-api'+method,
		data: data,
		header:header,
		method: 'POST'
	});
}

const get = (method, data) => {
	uni.showLoading({
		title: '加载中'
	});
	var header={
			'Accept': 'application/json',
			'Content-Type': 'application/x-www-form-urlencoded', //自定义请求头信息
		}
	header=setHeader(header)
	return request({
		url: apiBaseUrl + '/web-api'+method,
		data:data,
		header:header,
		method: 'GET'
	});
}
const setHeader = header => {
	let userToken = db.get("userToken");
	if (userToken) {
	  header[ 'X-Access-Token' ] = userToken // 让每个请求携带自定义 token 请根据实际情况自行修改
	}
	return header
}

//put
const put = (method, data) => {
	uni.showLoading({
		title: '加载中'
	});
	var header={
			'Accept': 'application/json',
			'Content-Type': 'application/json',
		}
	header=setHeader(header);
	
	return request({
		url: apiBaseUrl + '/web-api'+method,
		data: data,
		header:header,
		method: 'PUT'
	});

}
// 普通上传图片
export const uploadImage = (num, callback) => {
	var header={
			'Accept': 'application/json',
			'Content-Type': 'multipart/form-data',
			// 'Content-Type': 'application/x-www-form-urlencoded', //自定义请求头信息
		}
	header=setHeader(header);
	uni.chooseImage({
		count: num,
		success: (res) => {
			uni.showLoading({
				title: '上传中...'
			});
			let tempFilePaths = res.tempFilePaths
			for (var i = 0; i < tempFilePaths.length; i++) {
				uni.uploadFile({
					url: apiBaseUrl + '/web-api' +'/sys/common/upload',
					filePath: tempFilePaths[i],
					fileType: 'image',
					name: 'file',
					header: header,
					formData: {
						'method': 'images.upload',
						'upfile': tempFilePaths[i]
					},
					success: (uploadFileRes) => {
						console.log(uploadFileRes)
						callback();
					},
					fail: (error) => {
						if (error && error.response) {
							showError(error.response);
						}
					},
					complete: () => {
						setTimeout(function() {
							uni.hideLoading();
						}, 250);
					},
				});
			}
		}
	});
}


export {post,get}

api.js

import {get,post} from '@/config/config.js'
const randomImage = (params) => get('/sys/randomImage/'+params, null);
const extractRandom = (params)=>post("/iwrs/random/generate",params);
export {
  randomImage,
  extractRandom
}

调用

//mian.js
import * as Api from './api/api.js'
Vue.prototype.$api = Api;
//vue页面
this.$api.randomImage (param).then((res)=>{
				if(res.success){
					
				}else{
					
				}
			})

附赠一个图片上传

ChooseImage() {
			var that = this;
			this.$config.uploadImage(5, res => {
				if (res.success) {
					if (!item.pics) {
						item.pics = [];
					}
					item.pics.push({
						src: res.data.url.replace(/\\/g, '/'),
						image_id: res.data.image_id
					});
					this.$set(this.form.items, index, item);
					that.$common.successToShow(res.msg);
				} else {
					that.$common.errorToShow(res.msg);
				}
			});
		},

你可能感兴趣的:(uni-app)