学无先后,达者为师

网站首页 编程语言 正文

uni-app 使用escook/request-miniprogram插件发请求

作者:调调啊 更新时间: 2022-11-08 编程语言

一 , npm install @escook/request-miniprogram

用这个插件发请求的优点就是可以直接在main.js中设置请求拦截器和响应拦截器 , 还有根路径 , 比较方便

二 , main.js中


// 导入发请求的包,并挂载到uni身上
import {
	$http
} from '@escook/request-miniprogram'

uni.$http = $http


// 请求根路径 
$http.baseUrl = '/api' 


//请求拦截器
$http.beforeRequest = function(config) {
	

}

//响应拦截器
$http.afterRequest = function(response) {
	console.log(response)

	if (response.data.code == '0001') {
		uni.showToast({
			title: '您还没有登录喔',
			duration: 2000,
			icon: "none"
		});

		setTimeout(function() {
			uni.navigateTo({
				url: '../login/login'
			});
		}, 1000)


	} else {
		return
	}
}

二 , 需要发请求的.vue页面中

uni.$http.post('请求路径', 参数);

methods: {
			// 登录
			async formSubmit(e) {
                //参数
				const params = {
					username: e.detail.value.username,
					password: e.detail.value.password,	
				};
                // 开启loading
				uni.showLoading({
					title:"登录中"
				})
               //发送请求
				const {data: res} = await uni.$http.post('/login', params);
				
				if (res.code !== '0') {
					return uni.showToast({
						title: '用户名或密码错误',
						duration: 2000,
						icon: 'none'
					});
					return;
				} else {
					uni.showToast({
						title: '登录成功',
						duration: 2000,
						icon: 'none'
					});    
				}
			}
		}

原文链接:https://blog.csdn.net/weixin_49577940/article/details/121956987

栏目分类
最近更新