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

Love The Way You Lie 2023-10-02 20:41 119阅读 0赞

文章目录

    • 网络请求基本演练和封装
      • 网络请求基本演练
      • 网络请求配置域名
      • 网络请求的封装

网络请求基本演练和封装

网络请求基本演练

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






























































属性 类型 默认值 必填 说明
url string 开发者服务器接口地址
data string/object/ArrayBuffer 请求的参数
header Object 设置请求的 header,header 中不能设置 Referer。 content-type 默认为 application/json
timeout number 超时时间,单位为毫秒。默认值为 60000
method string GET HTTP 请求方法
dataType string json 返回的数据格式
responseType string text 响应的数据类型

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

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

data: 请求参数

method: 请求的方式

success: 成功时的回调

fail: 失败时的回调

网络请求API基本演练

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

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

  1. Page({
  2. data: {
  3. allCities: {
  4. }
  5. },
  6. // onLoad生命周期发送网络请求
  7. onLoad() {
  8. wx.request({
  9. // 发送网络请求的地址
  10. url: "http://123.207.32.32:1888/api/city/all",
  11. // 拿到请求的结果
  12. success: (res) => {
  13. // 将获取的结果保存到data中
  14. const data = res.data.data
  15. this.setData({
  16. allCities: data
  17. })
  18. },
  19. // 拿到错误信息
  20. fail: (err) => {
  21. console.log(err);
  22. }
  23. })
  24. }
  25. })

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

  1. Page({
  2. onLoad() {
  3. wx.request({
  4. url: 'http://123.207.32.32:1888/api/home/houselist',
  5. // 无论是POST请求还是GET请求, 参数都是在data中传递
  6. data: {
  7. page: 1
  8. },
  9. success: (res) => {
  10. console.log(res);
  11. },
  12. fail: (err) =>{
  13. console.log(err);
  14. }
  15. })
  16. }
  17. })

网络请求配置域名

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

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

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

域名只支持 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;

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


网络请求的封装

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

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

思路一: 封装成一个函数

  1. export function yqRequest(options) {
  2. return new Promise((resolve, reject) => {
  3. wx.request({
  4. ...options,
  5. success: (res) => {
  6. resolve()
  7. },
  8. fail: reject
  9. })
  10. })
  11. }
  • 这样我们发送网络请求就可以使用该函数, 使用该函数发送网络请求就可以通过Promise或者async和await获取结果

    import {

    1. yqRequest } from "../../service/index"

    Page({

    1. onLoad() {
    2. // 通过Promise获取结果
    3. yqRequest({
    4. url: "http://123.207.32.32:1888/api/city/all"
    5. }).then(res => {
    6. console.log(res);
    7. })
    8. yqRequest({
    9. url: 'http://123.207.32.32:1888/api/home/houselist',
    10. data: {
    11. page: 1
    12. }
    13. }).then(res => {
    14. console.log(res);
    15. })
    16. }

    })

    import {

    1. yqRequest } from "../../service/index"

    Page({

    1. onLoad() {
    2. // 此处调用封装的异步函数
    3. this.getCityData()
    4. this.getHouseListData()
    5. },
    6. // 使用async和await获取结果, 为了防止同步最好再封装成独立方法
    7. async getCityData() {
    8. const cityData = await yqRequest({
    9. url: "http://123.207.32.32:1888/api/city/all"
    10. })
    11. console.log(cityData);
    12. },
    13. async getHouseListData() {
    14. const houseListData = await yqRequest({
    15. url: 'http://123.207.32.32:1888/api/home/houselist',
    16. data: {
    17. page: 1
    18. }
    19. })
    20. console.log(houseListData);
    21. }

    })

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

  1. // 网络请求封装成类
  2. class YQRequest {
  3. // 传入配置的baseurl
  4. constructor(baseUrl) {
  5. this.baseUrl = baseUrl
  6. }
  7. request(options) {
  8. const {
  9. url } = options
  10. return new Promise((resolve, reject) => {
  11. wx.request({
  12. ...options,
  13. url: this.baseUrl + url,
  14. success: (res) => {
  15. resolve(res)
  16. },
  17. fail: reject
  18. })
  19. })
  20. }
  21. get(options) {
  22. return this.request({
  23. ...options, method: "get" })
  24. }
  25. post(options) {
  26. return this.request({
  27. ...options, method: "post" })
  28. }
  29. }
  30. export const yqRequest = new YQRequest("http://123.207.32.32:1888/api")
  • 使用类的实例发送网络请求同样可以通过Promise或者async和await获取结果(这里不再演示async和await了)

    import {

    1. yqRequest } from "../../service/index"

    Page({

    1. onLoad() {
    2. // 使用类的实例发送网络请求
    3. yqRequest.request({
    4. url: "/city/all"
    5. }).then(res => {
    6. console.log(res);
    7. })
    8. yqRequest.get({
    9. url: '/home/houselist',
    10. data: {
    11. page: 1
    12. }
    13. }).then(res => {
    14. console.log(res);
    15. })
    16. }

    })

发表评论

表情:
评论列表 (有 0 条评论,119人围观)

还没有评论,来说两句吧...

相关阅读