微信小程序 封装数据请求的方法

微信小程序封装数据请求的方法

  1. 需求:在使用微信小程序自带的请求方式的时候不习惯原始的数据请求方式,想要使用类似于axios封装的Promise
  2. 微信小程序的数据请求文档
  3. 封装的serve.js代码
    const serve = (options) => {
        return new Promise((resolve,reject) => {
            wx.request({
                url: options.url,
                method: options.method || "GET",
                data: options.data || {},
                success: (res) => {
                    resolve(res)
                },
                fail: (err) => {
                    reject(err)
                }
            })
        })
    }
    export default serve
    
  4. 使用方式
    // 首先导入封装的文件, 这里不可以使用绝对路径
    import serve from "../../serve/serve.js"
    Page({
    	onLoad: function (options) {
          serve({
              url: "http://httpbin.org/post",
              method: "post"
          }).then((res) => {
              console.log(res)
          }).catch((err) => {
              console.log(err)
          })
      	}
    })
    
    http://httpbin.org/post是使用的httpbin网站进行的数据模拟

你可能感兴趣的:(微信小程序)