uniapp的request请求Promise封装

1、根目录utils下的api,js文件

// myRequest({
// 	url: '/api/***********',
// 	method:'POST',
// 	date:{
// 	}
// })
const BASE_URL = ''
export const myRequest = (options) => {
	// console.log(options)
	// get / post 小写转大写
	let method = options.method.toUpperCase()
	// console.log(method)
	return new Promise((resolve, reject) => {
		uni.request({
			url: BASE_URL + options.url,
			method: method || 'GET',
			data: options.date || {},
			success: (res) => {
				resolve(res)
				console.log(res)
				if (res.data.statusCode !== 200) {
					return uni.showToast({
						title: '获取数据成功'
					})
				}
			},
			fail: (err) => {

				console.log(err)
				uni.showToast({
					title: '请求接口失败'
				})
			}
		})
	})
}

2、全局挂载,main.js引入

import {myRequest} from "@/utils/api.js"
Vue.prototype.$myRequest = myRequest; 

3、使用方法

            async aaa() {
                const res = await this.$myRequest({
                    url: 'https://APIkey.Net',
                    method : 'get'
                })
                // this.Saying = res.data.data.Saying
                console.log(res)
            } 


版权声明:本文为weixin_47724021原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。