request请求封装

1,新建utils文件下的reqest.js文件
2,export 抛出方法

export const baseURL = 'https://xxx/api/'

export const request = (options) => {
	return new Promise((resolve, reject) => {
		uni.request({
			url: baseURL + options.url, //接口地址:前缀+方法中传入的地址
			method: options.method || 'GET', //请求方法:传入的方法或者默认是“GET”
			data: options.data || {}, //传递参数:传入的参数或者默认传递空集合
			header: {
				'token': uni.getStorageSync("token") || "" //自定义请求头信息
			},
			success: (res) => {
				//返回的数据(不固定,看后端接口,这里是做了一个判断,如果不为true,用uni.showToast方法提示获取数据失败)
				if (res.data.code == 1) {
					resolve(res.data.data)
				} else {
					if(res.data.code== 401){
						uni.navigateTo({
							url:'/login/login'
						})
						uni.clearStorageSync()
					}
					reject(res.data.msg)
				}
				// 如果不满足上述判断就输出数据
			},
			// 这里的接口请求,如果出现问题就输出接口请求失败
			fail: (err) => {
				console.log(err)
				reject(err)
			}
		})
	})
}

二次封装

用于存放接口,新建api文件下的index.js文件

//引入请求方法
import {
	request
} from '@/utils/request.js'

//调用请求方法,再抛出,method:请求方式
export const getForumType = (a, b) => request({url: '接口地址',method: 'post',data: {a,b}})
export const sendForum = (data) => request({url: '接口地址',method: 'post',data: data})

页面使用

注意:async 方法无法在onload()方法中使用

//引入二次封装文件
import {
		getForumType ,
		sendForum 
	} from '@/api/index.js'
//调用二次封装的接口
methods: {
	async getForumType () {
		try {
			const res = await getBanner()
			console.log('请求回来的值', res)

		} catch (err) {
			uni.showToast({
				title: err,
				icon: 'none'
			})
		}
	},
}
Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐