request.js 1.48 KB
Newer Older
xinzhedeai's avatar
xinzhedeai committed
1
import { showCustomModal } from "./util";
xinzhedeai's avatar
xinzhedeai committed
2
import { BASEURL, REQUESTIMEOUT } from "./config";
xinzhedeai's avatar
xinzhedeai committed
3
console.log(BASEURL, 'BASEURLBASEURLBASEURL')
xinzhedeai's avatar
xinzhedeai committed
4 5
const BASE_URL = BASEURL;
const REQUEST_TIMEOUT = REQUESTIMEOUT;
6 7 8 9 10 11 12 13 14 15


export default function request(options) {
	return new Promise((resolve, reject) => {
		uni.request({
			url: options.url,
			method: options.method || 'GET',
			data: options.data || {},
			header: options.header || {
				'Content-Type': 'application/json',
xinzhedeai's avatar
xinzhedeai committed
16
				'Authorization': uni.getStorageSync('token')
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
			},
			success: (res) => {
				console.log(res, 'request')
				if (res.code === 200) {
					resolve(res.data);
				} else {
					reject(res);
				}
			},
			fail: (err) => {
				reject(err);
			}
		});
	});
}

uni.addInterceptor("request", {
	invoke(args) {
		// request 触发前拼接 url
		args.url = BASE_URL + args.url
	},
	success(res) {
		const {
			code,
			msg
		} = res.data;
		console.log('addInterceptor', code, msg)
xinzhedeai's avatar
xinzhedeai committed
44 45 46 47
		if(code === 401){
			showCustomModal({
				content: msg,
				success: function() {
xinzhedeai's avatar
xinzhedeai committed
48
					uni.getStorageSync('token', '')
xinzhedeai's avatar
xinzhedeai committed
49 50 51 52 53
					uni.reLaunch({ // 登录超时跳转登录页面
						url: "/pages/user/login"
					})
				}
			});
xinzhedeai's avatar
xinzhedeai committed
54
			return
xinzhedeai's avatar
xinzhedeai committed
55
		}
56 57 58 59 60 61 62 63 64
		if (code !== 200) {
			showCustomModal({
				content: msg,
			});
			// uni.navigateTo({
			// 	url: "/pages/login/login"
			// });
			return;
		}
xinzhedeai's avatar
xinzhedeai committed
65
		
66 67 68 69 70 71 72 73 74 75 76
		return Promise.resolve(res.data);
	},
	fail(err) {
		uni.showToast({
			title: "网络异常",
			icon: "error",
			duration: 2000
		});
		return Promise.reject(err);
	}
});