uniapp uview请求接口显示加载状态

uniapp yekong 2667℃

uniapp开发 使用uview http请求显示加载状态。

加载状态

uni.showLoading({
			title: 'loading'
})

代码封装

// 此vm参数为页面的实例,可以通过它引用vuex中的变量
import configs from './config.js'
module.exports = (vm) => {
	// 初始化请求配置
	uni.$u.http.setConfig((config) => {
		/* config 为默认全局配置*/
		config.baseURL = configs.baseUrl; /* 根域名 */
		return config
	})

	// 请求拦截
	uni.$u.http.interceptors.request.use((config) => { // 可使用async await 做异步操作
		config.header['Content-Type'] = 'application/json'
		config.data = config.data || {}
		// 根据custom参数中配置的是否需要token,添加对应的请求头
		// en-us 英文
		// zh-cn 中文
		uni.showLoading({
			title: 'loading'
		})
		config.header['X-Lang'] = uni.getStorageSync('Lang') ? uni.getStorageSync('Lang') : 'zh-cn'
		if (config?.custom?.auth) {
			if (uni.getStorageSync('token')) {
				config.header['x-token'] = uni.getStorageSync('token')
				// 可以在此通过vm引用vuex中的变量,具体值在vm.$store.state中
			} else {
				uni.redirectTo({
					url: '/pages/login/wxlogin'
				})
			}
		}
		return config
	}, config => { // 可使用async await 做异步操作
		return Promise.reject(config)
	})

	// 响应拦截
	uni.$u.http.interceptors.response.use((response) => {
		/* 对响应成功做点什么 可使用async await 做异步操作*/
		uni.hideLoading()
		const data = response.data
		if (response.cookies) {
			console.log(response.cookies)
			if (response.cookies.length != 0) {
				uni.setStorageSync('cookie', response.cookies[0]);
			}
		}
		// 自定义参数
		// const custom = response.config?.custom
		if (data.status != 200) {
			// 如果没有显式定义custom的toast参数为false的话,默认对报错进行toast弹出提示
			if (data.message) {
				// uni.$u.toast(data.message)
				uni.showToast({
					title: data.message,
					icon: 'none'
				});
			}

			if (data.status == 40000) {
				// uni.clearStorageSync()
				uni.$u.route('/pages/login/login')
			}
			if (data.code == 602) {
				// uni.clearStorageSync()
				uni.$u.route('/pages/login/wxlogin')
			}
		}
		return data === undefined ? {} : data
	}, (response) => {
		// 对响应错误做点什么 (statusCode !== 200)
		if (response.statusCode == 401) {
			uni.$u.route('/pages/login/wxlogin')
		}
		return Promise.reject(response)
	})
}

喜欢 (2)