uview封装 http请求

1.封装http请求 在common文件目录下,分别创建http.interceptor.js文件和baseurl.js文件

                   baseurl.js里导出 url 网址

export const BASE_URL = 'https://www.baidu.com'

                   http.interceptor.js里引入url网址,并配置参数和添加请求拦截

import {
	BASE_URL
} from "./baseurl"


/* 

config = {
	baseUrl: '', // 请求的本域名
	method: 'POST',
	// 设置为json,返回后会对数据进行一次JSON.parse()
	dataType: 'json',
	showLoading: true, // 是否显示请求中的loading
	loadingText: '请求中...', // 请求loading中的文字提示
	loadingTime: 800, // 在此时间内,请求还没回来的话,就显示加载中动画,单位ms
	originalData: false, // 是否在拦截器中返回服务端的原始数据
	loadingMask: true, // 展示loading的时候,是否给一个透明的蒙层,防止触摸穿透
	// 配置请求头信息
	header: {
		'content-type': 'application/json;charset=UTF-8'
	},
} 
 
 
 */

const install = (Vue, vm) => {
	// 此为自定义配置参数https://www.zhaoyangjing.com,
	Vue.prototype.$u.http.setConfig({
		baseUrl: BASE_URL,
		loadingText: '努力加载中~',
		loadingTime: 800,
		loadingMask: true,
		originalData: true, // 是否在拦截器中返回服务端的原始数据
		// 设置自定义头部content-type
		header: {
			'token': ''
		}
	});
	//请求拦截
	Vue.prototype.$u.http.interceptor.request = (config) => {
		// 引用token
		// token放在了Storage本地存储中,拦截是每次请求都执行的
		// 所以哪怕您重新登录修改了Storage,下一次的请求将会是最新值
		const token = uni.getStorageSync('token');
		// console.log(token, 'tttttttt');
		config.header.token = token;
		// 最后需要将config进行return
		return config;
	}
	// 响应拦截,每次请求结束都会执行本方法
	Vue.prototype.$u.http.interceptor.response = (res) => {

		if (res.data.code == 1) {
			// res为服务端返回值,可能有code,result等字段
			// 这里对res.result进行返回,将会在this.$u.post(url).then(res => {})的then回调中的res的到
			// 如果配置了originalData为true,请留意这里的返回值
			return res.data;
		} else if (res.data.code == 401) {
			// 401为token失效,这里跳转登录
			vm.$u.toast('登录过期,请重新登录');
			setTimeout(() => {
				// 此为uView的方法,详见路由相关文档
				vm.$u.route('/pages/longin/longin')
			}, 1000)
			return false;
		} else {
			// 如果返回false,则会调用Promise的reject回调,
			// 并将进入this.$u.post(url).then().catch(res=>{})的catch回调中,res为服务端的返回值
			vm.$u.toast(res.data.msg);
			return false;
		}
	}

}

export default {
	install
}

2.将文件引入到main.js

import httpInterceptor from '@/common/http.interceptor.js'
// 这里需要写在最后,是为了等Vue创建对象完成,引入"app"对象(也即页面的"this"实例)
Vue.use(httpInterceptor, app)

3.页面使用

guanbi() {
	this.$u.post('/api/index/commonConfig').then(res => {
	       console.log(this.kai)
	})
   },

  • 8
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

泥木马

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

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

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

打赏作者

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

抵扣说明:

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

余额充值