Use uniapp's native network method uni.request to encapsulate network requests

1. Create a folder in the project to store network requests (or create a file directly)

 2. The specific code for encapsulating network requests is as follows:

// 简单接口封装(加入token字段没起作用)

//域名或选取所有接口不变的那一部分
let baseURL = 'http://yqdh.test.site.ximengnaikang.com/pap/api'; 
let token = uni.getStorageSync('login_token')
// 默认是get请求
export const service = async function(args) {
	console.log(args,args.header, '这是给接口的数据')
    return await new Promise((resolve, reject) => {
        uni.showLoading({
            title: "加载中......"
        })
         uni.request({
            url: baseURL + args.url,
			method:args.method || 'GET',
            data: args.data,
            header: {
                //没能起到如果存在token就在header中加入token的作用,需要修改
				'Authorization': token ? `Bearer ${token}` : '',  
                //自定义初始化请求头信息
                'Content-Type': 'application/json;charset=utf-8', 
                //如果要给header添加字段的话则用剩余参数全部接收
				...args.header
            },
            success: (res) => {
                console.log('由于后端可能给的格式不一样,最好自己打印看看在处理')
                if (!res.data.status) {
                    uni.showToast({
                        title: res.data.msg
                    })
                }
                resolve(res.data)
            },
            fail: (err) => {
                uni.showToast({
                    title: "接口请求失败"
                })
                reject(err)
            },
            complete: () => {
                uni.hideLoading();
                console.log('完成请求了')
            }
        });
    })
}

3. Simple to use in the page

 

Guess you like

Origin blog.csdn.net/weixin_44191318/article/details/125378503