promise封装小程序api请求

在项目中我们使用请求 需要通过api封装

  • 为什么封装api

因为在项目中 请求使用的地方会有很多 不利于后期维护 如果我我们讲api封装出来 只需要维护api文件就可以了

这里以uniapp封装api来写小程序为例

第一步

  • 先在项目目录中创建一个utils文件夹 在该文件夹下创建一个js文件为请求的封装 代码如下
// 封装请求
const http = ({
    
    url, method='get', data=''}) => {
    
    
	return new Promise((resolve, reject) => {
    
    
		uni.request({
    
    
			method,
			url: `公共请求地址` + url,
			data,
			success(res) {
    
    
				resolve(res.data) // 将请求成功后得到的数据返回出去 可以用then方法接受到数据
			},
			
			fail(err) {
    
    
				reject(err) // 将请求失败后返回的信息 返回出去 可以用catch方法接受到
			},
			
			complete() {
    
    
				
			}
		})
	})
}

export default http;

第二步

  • 在utils文件夹下创建一个api.js 这里以请求轮播图数据的接口为例
import http from './http.js'

// 请求轮播图数据的接口
export const getSwiper = () => http({
    
    url: '你们自己的请求轮播图数据的接口地址'})

第三步

  • 在需要使用轮播图接口的文件中
	import {
    
     getSwiper } from '../../utils/api.js'
	export default {
    
    
		data() {
    
    
			return {
    
    
				swiper: []
			}
		},
		async created() {
    
    
			let {
    
    message} = await getSwiper() // message就是我们请求完成后获取的数据信息
			this.swiper = message
		},
	}

猜你喜欢

转载自blog.csdn.net/wjw0125/article/details/122289193