The WeChat applet uniapp combines the promise to encapsulate the request api, and further encapsulates the request.

1. The first step is to create a utils file > index.js file in the root directory and insert the following code.

const basUrl = 'https://api-hmugo-web.itheima.net/api/' // 设置公共的域名
const request = (params)=>{
	uni.showLoading({ // 显示加载中  微信 就把 uni 改成 wx
		title:'加载中'
	})
	// 我们搭配 Promise 进一步封装
	return new Promise((resolve,reject)=>{
		// Promise 一种异步编程的解决方案 支持链式调用 可以将异步操作队列化 
		// Promise 状态 Pending --> Fulfilled 或者 Pending --> Rejected,Fulfilled 和 Rejected 是最终状态,不可以进行第二次修改;
		uni.request({
			url:basUrl + params.url, // 拼接 params 传过来的 url
			data:params.data, // 拼接 params 传过来的 参数
			method:params.method || 'GET',  //  传过来的 请求方式 默认 get
			success:(res)=>{ // 成功的回调函数
				resolve(res.data)  // 成功了  resolve 返回 就可以 .then 调用了
			},
			fail:reject, // 失败 .catch可以捕获到
			complete() { // 接口调用结束的回调函数(调用成功、失败都会执行)	
				uni.hideLoading()
			},
			// 对于 POST 方法且 header['content-type'] 为 application/x-www-form-urlencoded 的数据,会将数据转换成 query string
			header:{
				'content-type':'application/x-www-form-urlencoded'
			}
		})
	})
}
export default request // es6 模块化导出 

2. Create an app file > index.js

import request from "../utils/request.js" // 引入

module.exports = { // 导出
	// 获取轮播图的数据
    getBanner: async ()=>{
		return await request({url:'public/v1/home/swiperdata'})
	},

	// 详情请求 带参数的
	getDetail:async(params)=>{
		return await request({url:'public/v1/goods/detail',data:params})
	},

	
}

 3. You can use it on the page

	import { getDetail } from '../../app/index.js'
		
	onLoad(id) {
		getDetail({
			goods_id: id.id
		}).then(res => {
			console.log(res.message)
			this.obj = res.message
		})
	},

Handjob is not easy _s-en

Guess you like

Origin blog.csdn.net/qq_54753561/article/details/122016415