uniapp-uni.reques请求拦截封装


1、config.js   在项目根目录创建config/config.js

const config  ={
	baseURL: 'https://xxx.xxx.com', //接口域名
}

if (process.env.NODE_ENV === 'development') { //开发模式
	config.baseURL =  "https://chunxiang.yunzanet.com" //接口域名

}
export default config

2、在项目根目录创建api目录(根据个人习惯命名),并创建index.js

index.js代码如下

import store from '@/store/index'
import Vue from 'vue';

const globalRequest = (api, method, options) => {
	let loadingTimer = null;
	const option = {
		loading: true, //是否显示loading
		delayed: true, //是否延时显示loading
		loading_text: 'loading', //是否延时显示loading
		params: {}
	}
	if (options) {
		if (options.loading !== undefined) option.loading = options.loading
		if (options.delayed !== undefined) option.delayed = options.delayed
		if (options.loading_text !== undefined) option.loading_text = options.loading_text
		if (options.params !== undefined) option.params = options.params
	}

	// 判断是不是全域名
	let regex = /^http/;
	let request_url = Vue.prototype.$config.baseURL + api;
	if (regex.test(api)) request_url = api
	const headers = {
		// "Content-Type": 'application/x-www-form-urlencoded',
		"token": uni.getStorageSync('token') || '', //token
	}

	if (option.loading && !option.delayed) {
		// 立即显示loading
		store.commit("loadingShow", option.loading_text)
	} else if (option.loading && option.delayed) {
		// 延时显示loading
		loadingTimer = setTimeout(() => {
			console.log("显示弹窗");
			store.commit("loadingShow", option.loading_text)
		}, 1000)
	}

	return new Promise(function(resolve, reject) {
		uni.request({
			url: request_url,
			method: method,
			data: option.params,
			dataType: 'json',
			withCredenttials: true,
			header: headers,
			success: function(res) {
				clearTimeout(loadingTimer)
				store.commit("loadingHide") //隐藏loading
				if (res.statusCode == 200) { //浏览器200
					switch (res.data.code) {
						case 1:
							resolve(res.data)
							break;
						case 200:
							resolve(res.data)
							break;
						case 10001:
							store.commit("loginout")
							uni.reLaunch({
								url: "/pages/login/index"
							})
							reject(res.data)
							break;
						case 1003:
							store.commit("loginout")
							uni.reLaunch({
								url: "/pages/login/index"
							})
							reject(res.data)
							break;
						case 2005:
							store.commit("loginout")
							uni.reLaunch({
								url: "/pages/login/index"
							})
							reject(res.data)
							break;
						default:
							reject(res.data) // 返回失败
							break;
					}
				} else if (res.statusCode == 401) {
					store.commit("loginout")
					uni.reLaunch({
						url: "/pages/login/index"
					})
					reject(res.data)
				} else {
					reject({ message: '网络错误' }) // 浏览器处理不是200
				}
			},
			fail: (err) => {
				clearInterval(loadingTimer)
				store.commit("loadingHide") //隐藏loading
				if (store.state.network) {
					uni.showModal({
						content: '请检查网络',
						showCancel: false,
					});
					store.commit('setNetwork', false)

					setTimeout(() => {
						store.commit('setNetwork', true)
					}, 5000)
				}
				reject({ msg: '网络错误' })
			}
		})
	})
}


const api = {
	post: (api_path, options) => globalRequest(api_path, 'POST', options),
	get: (api_path, options) => globalRequest(api_path, 'GET', options)
}

export default api

3、项目根目录store/index.js 文件

import Vue from 'vue'
import Vuex from 'vuex'
import api from "@/api/index.js"
Vue.use(Vuex)
const store = new Vuex.Store({
	state: {
		network: true,
		token: uni.getStorageSync('token') || null,
		loading: false, //加载框是否正在显示
		...
	},
	mutations: {
		setNetwork(state, provider) {
			state.network = provider;
		},
		loadingShow(state, provider) {
			if (state.loading === false) {
				uni.showLoading({
					title: provider
				})
				state.loading = true
			}
		},
		loadingHide(state) {
			setTimeout(function() {
				uni.hideLoading();
				state.loading = false
			}, 500);
		},
		// 登录
		login(state, provider) {
			uni.setStorageSync('token', provider);
			state.token = provider;
		},
		//登出
		loginout(state) {
			uni.$emit('TIMLoginOut') //TIM退出登录
			state.user_info = null;
			state.token = null;
			uni.clearStorageSync()
		},
		
		
	},
})
export default store

4、main.js

import App from './App'
import Vue from 'vue'




import store from './store' //引入vuex


import config from './config/config.js'
Vue.prototype.$config = config

import api from './api/index.js'
Vue.prototype.api = api



Vue.config.productionTip = false
App.mpType = 'app'
const app = new Vue({
	store,
	...App
})
app.$mount()
export default app;

5、项目中引用 test.vue

<template>
	<view class="page-height">
		...

	</view>
</template>
<script>
export
default {
        methods:
        {
            onLogin() {
                const params = {
                    username: 'xxxxxx',
                    password: 'xxxxxx'
                }
                this.api.post("/api/wanlshop/user/login", {
                    params: params
                }).then(res = >{...自己写逻辑
                }).
                catch(err = >{

                    this.apiErr(err) //你自己封装全局方法处理报错信息
                })
            }
        }
    }
</script>


上一篇:uniapp-更新升级-wgt包热更新-整包更新-遮盖原生导航及tabbar
下一篇:外包项目-外卖跑腿