zl程序教程

您现在的位置是:首页 >  其他

当前栏目

【小程序】网络请求API介绍及网络请求的封装

2023-04-18 14:24:44 时间

网络请求基本演练和封装

网络请求基本演练

微信提供了专属的API接口,用于网络请求: wx.request(Object object)

属性类型默认值必填说明
urlstring开发者服务器接口地址
datastring/object/ArrayBuffer请求的参数
headerObject设置请求的 header,header 中不能设置 Referer。 content-type 默认为 application/json
timeoutnumber超时时间,单位为毫秒。默认值为 60000
methodstringGETHTTP 请求方法
dataTypestringjson返回的数据格式
responseTypestringtext响应的数据类型

上面众多属性中比较关键的几个属性如下:

url: 必传, 不然请求什么.

data: 请求参数

method: 请求的方式

success: 成功时的回调

fail: 失败时的回调

网络请求API基本演练

一般我们都是在页面的onLoad生命周期中发送网络请求

直接通过wx.request(Object object)发送无参数GET请求:

Page({
	data: {
		allCities: {}
	},
  // onLoad生命周期发送网络请求
	onLoad() {
		wx.request({
			// 发送网络请求的地址
			url: "http://123.207.32.32:1888/api/city/all",
			// 拿到请求的结果
			success: (res) => {
				// 将获取的结果保存到data中
				const data = res.data.data
				this.setData({
					allCities: data
				})
			},
			// 拿到错误信息
			fail: (err) => {
				console.log(err);
			}
		})
	}
})

直接通过wx.request(Object object)发送有参数GET请求:

Page({
	onLoad() {
		wx.request({
			url: 'http://123.207.32.32:1888/api/home/houselist',
			// 无论是POST请求还是GET请求, 参数都是在data中传递
			data: {
				page: 1
			},
			success: (res) => {
				console.log(res);
			},
			fail: (err) =>{
				console.log(err);
			}
		})
	}
})

网络请求配置域名

每个微信小程序需要事先设置通讯域名,小程序只可以跟指定的域名进行网络通信

小程序登录后台 – 开发管理 – 开发设置 – 服务器域名;

服务器域名请在 「小程序后台 - 开发 - 开发设置 - 服务器域名」 中进行配置,配置时需要注意

域名只支持 https (wx.request、 wx.uploadFile、 wx.downloadFile) 和 wss (wx.connectSocket) 协议;

域名不能使用 IP 地址(小程序的局域网 IP 除外)或 localhost;

可以配置端口,如 https://myserver.com:8080,但是配置后只能向 https://myserver.com:8080 发起请求。如果向https://myserver.com、 https://myserver.com:9091 等 URL 请求则会失败。

如果不配置端口。如 https://myserver.com,那么请求的 URL 中也不能包含端口,甚至是默认的 443 端口也不可以。如果 向 https://myserver.com:443 请求则会失败。

域名必须经过 ICP 备案;

出于安全考虑, api.weixin.qq.com 不能被配置为服务器域名,相关 API 也不能在小程序内调用。 开发者应将 AppSecret 保存到后台服务器中,通过服务器使用 getAccessToken 接口获取 access_token,并调用相关 API;

不支持配置父域名,使用子域名。


网络请求的封装

小程序提供的网络请求用起来是很繁琐的, 并且容易产生回调地狱, 因此我们通常会对小程序的网络请求进行封装

封装网络请求有两个思路:

思路一: 封装成一个函数

export function yqRequest(options) {
	return new Promise((resolve, reject) => {
		wx.request({ 
			...options,
			success: (res) => {
				resolve()
			},
			fail: reject
		 })
	})
}
  • 这样我们发送网络请求就可以使用该函数, 使用该函数发送网络请求就可以通过Promise或者async和await获取结果
import { yqRequest } from "../../service/index"

Page({
	onLoad() {
		// 通过Promise获取结果
		yqRequest({
			url: "http://123.207.32.32:1888/api/city/all"
		}).then(res => {
			console.log(res);
		})

		yqRequest({
			url: 'http://123.207.32.32:1888/api/home/houselist',
			data: {
				page: 1
			}
		}).then(res => {
			console.log(res);
		})
	}
})
import { yqRequest } from "../../service/index"

Page({
	onLoad() {
		// 此处调用封装的异步函数
		this.getCityData()
		this.getHouseListData()
	},

	// 使用async和await获取结果, 为了防止同步最好再封装成独立方法
	async getCityData() {
		const cityData = await yqRequest({
			url: "http://123.207.32.32:1888/api/city/all"
		})
		console.log(cityData);
	},
	async getHouseListData() {
		const houseListData = await yqRequest({
			url: 'http://123.207.32.32:1888/api/home/houselist',
			data: {
				page: 1
			}
		})
		console.log(houseListData);
	}
})

思路一: 封装成类(封装成类具备更强的扩展性)

// 网络请求封装成类
class YQRequest {
	// 传入配置的baseurl
	constructor(baseUrl) {
		this.baseUrl = baseUrl
	}

	request(options) {
		const { url } = options
		return new Promise((resolve, reject) => {
			wx.request({ 
				...options,
				url: this.baseUrl + url,
				success: (res) => {
					resolve(res)
				},
				fail: reject
			})
		})
	}

	get(options) {
		return this.request({ ...options, method: "get" })
	}

	post(options) {
		return this.request({ ...options, method: "post" })
	}
}

export const yqRequest = new YQRequest("http://123.207.32.32:1888/api")
  • 使用类的实例发送网络请求同样可以通过Promise或者async和await获取结果(这里不再演示async和await了)
import { yqRequest } from "../../service/index"

Page({
	onLoad() {
		// 使用类的实例发送网络请求
		yqRequest.request({
			url: "/city/all"
		}).then(res => {
			console.log(res);
		})

		yqRequest.get({
			url: '/home/houselist',
			data: {
				page: 1
			}
		}).then(res => {
			console.log(res);
		})
	}
})