request.js 4.42 KB
import config from '@/config.js'
import {
	pcLogin,
	getNowOpenId,
	initData,
	showLogin,
	h5LoginAuto
} from './login'

const excludeUrls = ['/system/wx/getUserInfo']

// 获取Token
function getToken() {
	try {
		const token = uni.getStorageSync('token');
		if (token) {
			return token
		} else {
			return ''
		}
	} catch (e) {
		console.log(e)
	}
}

// 获取请求头
function getHeaders() {
	const header = {
		"isToken": false,
		'content-type': 'application/x-www-form-urlencoded'
	}

	return header
}

let request = function(req) {
	req.method = req.method.toUpperCase()
	// if (!['GET', 'POST', 'PUT', 'DELETE'].includes(req.method)) {
	if (!['GET', 'POST'].includes(req.method)) {
		uni.showToast({
			title: `暂不支持的请求方式: ${req.method}`,
			icon: 'none'
		});
		return
	}

	// if (req.method == 'POST' && !req.hideLoding) {
	// 	uni.showLoading({
	// 		title: '提交中...'
	// 	})
	// }


	const token = getToken()
	let tempUrl = req.url

	let url, data
	if (config.localPort) {
		//生产环境
		// const baseUrl = location.origin + '/jsintszxd/request'
		//本地离线环境
		const baseUrl = config.localPort + '/jsintszxd/request'

		if (req.method === 'POST') {
			if (token) {
				req.params.userNo = token
			}

			url = baseUrl
			data = {
				appSecretId: config.appSecretId,
				restApi: encodeURIComponent(tempUrl),
				params: 'jsonBody=' + JSON.stringify(req.params)
			}
		} else {
			if (token) {
				if (tempUrl.indexOf('?') > -1) {
					tempUrl += '&userNo=' + token
				} else {
					tempUrl += '?userNo=' + token
				}
			}
			if (req.params) {
				for (const key of Object.keys(req.params)) {
					if (tempUrl.indexOf('?') > -1) {
						tempUrl += `&${key}=${req.params[key]}`
					} else {
						tempUrl += `?${key}=${req.params[key]}`
					}
				}
			}
			url = `${baseUrl}?appSecretId=${config.appSecretId}&restApi=${encodeURIComponent(tempUrl)}`
		}
	} else {
		if (req.method === 'POST') {
			if (token) {
				req.params.userNo = token
			}

			data = {
				jsonBody: JSON.stringify(req.params)
			}
		} else {
			if (req.params) {
				for (const key of Object.keys(req.params)) {
					if (tempUrl.indexOf('?') > -1) {
						tempUrl += `&${key}=${req.params[key]}`
					} else {
						tempUrl += `?${key}=${req.params[key]}`
					}
				}
			}
		}
		url = config.baseUrl_api + tempUrl
	}

	return new Promise((resolve, reject) => {
		uni.request({
			url: url,
			method: req.method,
			data: data,
			header: getHeaders()
		}).then(res => {
			switch (res.statusCode) {
				case 200:
					let tempRes
					if (config.localPort) {
						tempRes = res.data
					} else {
						tempRes = res
					}

					const resData = tempRes.data || {};
					if (resData.code == 200) {
						resolve(resData)
					} else {
						//登录超时
						if (resData.code == 60002 || resData.code == 60001) {
							showLogin()
						} else if (resData.code == 401) {
							h5LoginAuto()
								.then(() => {
									uni.hideLoading();
									uni.redirectTo({
										url: getCurrentPages()[getCurrentPages()
											.length - 1].$page.fullPath
									})
								})
						} else {
							if (!excludeUrls.includes(req.url)) {
								uni.showToast({
									title: resData.msg || resData.error,
									icon: 'none',
									duration: 3000
								})
							}
						}
						reject(tempRes)
					}
					break
				default:
					reject(tempRes)
			}
		}).catch(res => {
			reject(res)
		}).finally(() => {
			// if (req.method == 'POST' && !req.hideLoding) {
			// 	uni.hideLoading()
			// }
		})
	})
}

function reLogin() {
	const currUser = uni.getStorageSync('currUser') || {}
	if (currUser.openId) {
		const accountInfo = uni.getAccountInfoSync()
		pcLoginByOpenId(accountInfo.miniProgram.appId, currUser.openId)
			.then((res) => {
				let user = res.data;
				uni.setStorageSync('token', user.token);
				uni.setStorageSync('currUser', user);

				uni.showToast({
					title: '一走神把您的操作遗漏了,请重试',
					icon: 'none'
				})
			}).catch(() => {
				uni.showToast({
					title: '服务异常,请稍后重试',
					icon: 'none'
				})
			})
	}
}

function pcLoginByOpenId(appId, openId) {
	return request({
		url: "/system/wx/loginByOpenId",
		method: "POST",
		params: {
			appId: appId,
			openId: openId
		}
	})
}


export default request;