微信小程序中wx.request()发起网络请求

267 阅读1分钟

wx.request()

发起 HTTPS 网络请求。官方文档

常用参数

  1. url:开发者服务器接口地址。注意必须是在小程序管理后台开发管理中服务器域名配置过的域名才能使用。
  2. data:请求的参数。类型stringobjectArrayBuffer
  3. header:设置请求的 header,content-type默认为application/json
  4. timeout:超时时间,单位为毫秒。默认值为 60000。
  5. method:HTTP 请求方法,注意要全部大写。
  6. responseType:响应的数据类型,默认text响应的数据为文本、arraybuffer响应的数据为 ArrayBuffer二进制流如文件流视频流等。
  7. success:接口调用成功的回调函数。
  8. fail:接口调用失败的回调函数。
  9. complete:接口调用结束的回调函数(调用成功、失败都会执行)。

示例

    wx.request({
      url: "https://tzof.net:999/login",
      method: "GET",
      // 请求参数
      data: {
        username: 'blxh',
        password: 'blxh'
      },
      // 请求头
      header: {},
      // 成功执行的回调
      success: (res) => {
        console.log(res);
        // 关闭loading框
        wx.hideLoading();
      },
      // 失败执行的回调
      fail: (err) => {
        console.log(err);
      },
      // 不管调用成功还是失败都会执行
      complete: (res) => {
        console.log(res);
      },
    });

image.png