uniapp原生请求二次封装

548 阅读1分钟

原因:

在编写uniapp应用不建议使用axios,不然打包的小程序或者App应用,发送网络请求可能出现问题。要安装对应的请求适配插件才能解决,且适配插件和请求插件的版本需要匹配才行,因此封装uniapp原生的请求方法更为方便。

代码:

request.js
import baseUrl from './baseUrl.js'
import {
	tokenName,
	getToken
} from '@/utils/auth.js'
import {
	useLoginOut
} from '@/hooks/useLoginOut.js'

function doRequest(url, data, showLoading, method = 'GET', timeout = 60000) {
	showLoading && uni.showLoading({
		mask: true
	})
	return new Promise((resolve, reject) => {
		uni.request({
			data: data,
			url: baseUrl + url,
			method: method,
			header: {
				[tokenName]: getToken(),
			},
			timeout: timeout,
			// todo : 与后端协商data.code
			success: (res) => {
				if (res.statusCode === 200) {
					if (res.data.code === 200 || res.data.code === 201) {
						resolve(res.data)
					} else if (res.data.code === 401) {
						useLoginOut()
					} else {
						uni.showToast({
							icon: 'none',
							title: res.data.msg || '服务器出错'
						})
						reject(res)
					}
				} else {
					uni.showToast({
						icon: 'none',
						title: res.data.msg || '服务器出错'
					})
					reject(res)
				}
			},
			fail: (err) => {
				uni.showToast({
					icon: 'none',
					title: '网络请求失败'
				});
				reject(err)
			},
			complete: () => {
				uni.hideLoading()
			}
		})
	})
}

const request = {
	post: (url, data, showLoading=true, timeout) => {
		return doRequest(url, data, showLoading, 'POST', timeout)
	},
	get: (url, data, showLoading=true) => {
		return doRequest(url, data, showLoading, 'GET')
	},
	put: (url, data, showLoading=true) => {
		return doRequest(url, data, showLoading, 'PUT')
	},
	delete: (url, data, showLoading=true) => {
		return doRequest(url, data, showLoading, 'DELETE')
	},
}

export default request

auth.js
export const tokenName = 'token'

export function getToken(){
	return uni.getStorageSync(tokenName)
}

export function setToken(token){
	uni.setStorageSync(tokenName,token)
}

export function removeToken(token){
	uni.removeStorageSync(tokenName)
}
useLoginOut.js
import { removeToken } from "@/utils/auth"

export const useLoginOut = function(toast = true) {
	removeToken()
	uni.reLaunch({
		url: '/pages/login/login'
	})
	if (toast) {
		uni.showToast({
			title: '请重新登录',
			icon: 'none'
		})
	}
}