uni-app的http请求的全局配置及拦截器配置

// 此vm参数为页面的实例,可以通过它引用vuex中的变量
module.exports = (vm) => {
	// 初始化请求配置
	uni.$u.http.setConfig((config) => {
		/* config 为默认全局配置*/
		config.baseURL = 'https://api.shop.eduwork.cn' /* 根域名 */
		// config.header = {
		// 	'Content-Type': 'application/x-www-form-urlencoded'
		// }
		config.timeout = 10000
		return config
	})

	// 请求拦截
	uni.$u.http.interceptors.request.use((config) => { // 可使用async await 做异步操作
		if (vm.$store.state.login.token_type && vm.$store.state.login.token)
			config.header['Authorization'] = vm.$store.state.login.token_type + vm.$store.state.login.token
		else {
			vm.$u.route({
				url: 'pages/login/login',
			})}
		return config
	}, config => { // 可使用async await 做异步操作
		return Promise.reject(config)
	})

	// 响应拦截
	uni.$u.http.interceptors.response.use((response) => {
		/* 对响应成功做点什么 可使用async await 做异步操作*/
		const {
			statusCode,
			data,
		} = response;
		if(response.data){
			if (200 <= statusCode < 300) return data
			else if (statusCode === 400) {
				vm.$u.toast(data.message)
				return false
			} else if (statusCode === 401) {
				vm.$u.toast('验证失败,请重新登录')
				setTimeout(() => {
					vm.$u.route('@/pages/login/login')
				}, 1000)
			} else if (statusCode === 400) {
				const {
					errors
				} = data
				vm.$u.toast(Object.values(errors)[0][0])
				return false
			} else return data.message
		}
		else{
			return response
		}

	}, (response) => {
		// 对响应错误做点什么 (statusCode !== 200)
		return Promise.reject(response)
	})

	//增加patch请求
	vm.$u.patch = (url, params = {}) => {
		// 模拟patch请求
		const _params = {
			...params,
			_method: 'PATCH'
		}
		console.log(uni.$u.http.post);
		return uni.$u.http.post(url, _params)
	}
}

  • 2
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

鳕鱼&羚羊

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值