uni-app封装公共请求,带token等参数

为了使开发时,api请求统一写法,简单快捷。参考网上的资料封装了个公共请求,带token参数。

1、在工程目录下新建个common文件夹(有的就不需了),在common目录下新增request.js。

//请求函数
const request = (url = '', data = {},type = 'POST', header = {}) => {
	// 缓存中获取token 
	 data.token = data.token? data.token:uni.getStorageSync('token');
	 //请求地址
	 var baseUrl =  'http://localhost:8022/api/';  
    return new Promise((resolve, reject) => {
        uni.request({
            method: type,
            url: baseUrl +url,
            data: data,
            header: header,
            dataType: 'json',        
        }).then((response) => {
            uni.hideLoading();
            uni.stopPullDownRefresh();
            let [error, res] = response;
			
			console.log(res,'res');
            if(res.data.code == 200){
                setTimeout(function () {
                    resolve(res.data);
                }, 1000);
            }else if(res.data.code == -200){   //token失效时重新登录
                uni.showToast({
                    title:res.data.msg,
                    image:'../../static/public/close.png',
                    duration: 2000,
                });
				setTimeout(function(){
					uni.navigateTo({
					    url: '/pages/user/login',
						complete(e){
							console.log(e,'eeeeeeeeee')
						}
					});
				},1000);
				
            } else if(res.data.code == -100){   //-100时返回处理
			uni.showToast({
			    title:res.data.msg,
			    duration: 1000,
			});
			setTimeout(function () {
				//回调
			    resolve(res.data);
			}, 1000);
			
            }else {  //其它code 返回提示
                uni.showToast({
                    title:res.data.msg,
                    image:'../../static/public/close.png',
                    duration: 2000,
                });
            }
        }).catch(error => {
            uni.hideLoading();
            uni.stopPullDownRefresh();
            let [err, res] = error;
            reject(err)
			console.log(error ,'请求返回error')
        })
    });
}

//定义对象
var api = {
	request
};

export default api

2、在 main.js 中引入、定义

import request from 'common/request.js'  //引入封装全局




Vue.prototype.$api = request  

3、实例中,使用

this.$api.request('list', {
					time: '2021-11-10'                
                }, 'get').then((res) => {
					console.log(_res, 'res=============res');
				});

猜你喜欢

转载自blog.csdn.net/u014538997/article/details/121244305