Verwendung der Anforderungskapselungsschnittstelle von Uniapp

1. Erstellen Sie die Datei „request.js“.

Fügen Sie hier eine Bildbeschreibung ein

2.Grundlegende Verwendung

2.1 request.js

//这里是抛出去的意思
export default{
    
    
    a:1
}

2.2 Anrufernutzung

import $http from '@/common/api/request.js' // 先import引入

console.log($http.a) // 1 

3. Erweiterte Verwendung

3.1 request.js

// 这里是抛出去的意思
export default {
    
    
	a:1,
	// 这是一个公共模板
	common:{
    
    
		baseUrl:"http://192.168.126.1:3000/api",
		// 前端穿个后端的数据
		data:{
    
    },
		// 设置请求的 header
		head:{
    
    
			'content-type':"application/json",
			'content-type':"application/x-www-form-urlencoded"
		},
		// 默认的是get请求
		method:"GET",
		dataType:"json"
	},
	// 这是一个方法,request默认传进来的是对象,防止一些错误
	request(options={
     
     }){
    
    
		
		// 加载框
		// uni.showLoading({
    
    
		// 	title:'加载中'
		// }),
		
		// 传进来的url拼接上方的公共url
		options.url=this.common.baseUrl+options.url
		// 要是接口使用的时候传过来了就是用第一个 则 使用上方的公共模板
		options.data=options.data || this.common.data
		options.head=options.head || this.common.head
		options.method=options.method || this.common.method
		options.dataType=options.dataType || this.common.dataType
		// 返回一个promise res是成功 rej是失败
		return new Promise((res,rej)=>{
    
    
			// 这个是真正用来请求的
			uni.request({
    
    
				...options,
				success:(result) => {
    
    
					// 要是404就是失败
					if(result.statusCode !=200){
    
    
						return rej()
					}
					// 成功拿到数据之后就会隐藏加载框
					// setTimeout(function(){
    
    
					// 	uni.hideLoading()
					// },1000)
					// 接收url的数据
					let data=result
					// 成功返回数据给用的地方
					res(data)
				}
			})
		})
		
	}
}

3.2 Anrufernutzung

import $http from '@/common/api/request.js' // import引入

$http.request({
    
    
	url:"/index_list", //这里只传递url,其他数据默认(在request.js中common公共模板中)
}).then((res)=>{
    
     //这里是调用接口成功的
	console.log(res) //成功返回url接口的数据
	uni.showToast({
    
     //这是一个提示框信息
		title: '请求成功',
		icon: 'none',
		duration: 2000
	})
}).catch((res)=>{
    
     //这里是调用接口失败的
	uni.showToast({
    
     //这是一个提示框信息
		title:'请求失败',
		icon:'none'
	})
})

Supongo que te gusta

Origin blog.csdn.net/m0_62496369/article/details/127203377
Recomendado
Clasificación