uni-app封装数据请求

准备

新建文件目录如下

在这里插入图片描述

代码


// 根据自己的数据库请求端口
const BASE_URL = 'http://localhost:8082'
export const myRequest = (options) => {
    
    
	return new Promise((resolve, reject) => {
    
    
		uni.request({
    
    
			url: BASE_URL + options.url,
			method: options.method || 'GET',
			data: options.data || {
    
    },
			success: (res) => {
    
    
				if (res.data.status !== 0) {
    
    
					return uni.showToast({
    
    
						title: '数据获取失败'
					})
				}
				resolve(res)
			},
			fail: (err) => {
    
    
				uni.showToast({
    
    
					title: '请求接口失败'
				})
				reject(err)
			}
		})
	})
}

main.js文件添加如下语句

import {
    
    myRequest} from './util/api.js'
Vue.prototype.$myRequest = myRequest

在所欲使用的文件写如下代码

methods: {
    
    
			//获取轮播图数据
		  async	getSwipers(){
    
    
				console.log('获取轮播图数据')
				const res= await this.$myRequest({
    
    
					url:'/api/getlunbo'
				})
				console.log(res)
				// 根据自己的数据需求填写
				this.swipers=res.data.message
		
			}
		}

猜你喜欢

转载自blog.csdn.net/weixin_44135909/article/details/112385048