美文网首页
小程序封装ajax及使用方法

小程序封装ajax及使用方法

作者: 刘其瑞 | 来源:发表于2019-07-23 20:09 被阅读0次

微信小程序提供了网络请求方法,但是用起来不太方便,就自己封装了下。

封装源码

// 基准路径
const baseUrl = 'https://xxxxxxxxxxx'
// 1.0 返回一个 promise 对象
function request(url, method = 'GET', data = {}, header = {}) {
    return new Promise((resolve, reject) => {
        wx.showLoading({
            title: '加载中'
        })
        // 2.0 完成逻辑处理
        wx.request({
            url: baseUrl+url,
            method: method,
            data: data,
            header,
            success: res => {
                resolve(res)
                wx.hideLoading()
            },
            fail: err => {
                reject(err)
            }
        })
    })
}

// 封装一个单独的 get 方法
request.get = function (url, data = {}) {
    return request(baseUrl+url, 'GET', data)
}

// 封装一个单独的 post 方法
request.post = function (url, data = {}) {
    return request(baseUrl+url, 'POST', data)
}

// 封闭一个验证是否登录的方法
request.auth = function (url, method, data = {}) {
    // 得到 token
    var token = wx.getStorageSync('token')
    if (!token) {
        // 如果不存在,跳转到登录页面
        wx.navigateTo({
            url: '/pages/auth/main'
        })
        return new Promise(() => { })
    }
    // 如果存在,就直接发送请求(在请求头中带上 token)
    return request(url, method, data, { "Authorization": token })
}

// 3.0 暴露给外界
export default request

引用

//在main或封装的公共js中把request挂载到全局
import request from'./utils/myrequest'
//挂载
Vue.prototype.$request = request
//使用
    $request('/categories')
      .then(res => {
        console.log(res)
        that.setData({
          // 修改数据
        })
      })
// 导入 myrequest
import request from '../../utils/myrequest.js'

// 第一种get请求方法(封装时已默认设置get请求)
    request('/categories')
      .then(res => {
        console.log(res)
        that.setData({
          // 修改数据
        })
      })
// 第二种get请求方法
request.get('/detail', {
        goods_id: this.goods_id
      }).then(res => {
        console.log(res.data.data)
        that.setData({
          // 修改数据
        })
      })
// 第三种get请求方法
request('/catitems','GET').then(res =>{
    this.dataList = res.data.message
})

// 发送post请求
request.post('/wxlogin', {
    name: 'xiaoming',
        age: 18
})
    .then(res => {
        console.log(res.data.data)
                  that.setData({
                     // 修改数据
                  })
    })

同时请求多个ajax的便捷方法

methods: {
    async getData() {
      // 得到轮播图的数据
      try {
        const res = await request('/swiperdata')
        this.imgList = res.data.data
      } catch (err) {
        console.log('将错误记录到日志文件中')
      }
      // 得到分类的数据
      try {
        const res = await request('/catitems')
        this.cateList = res.data.data
      } catch (err) {
        console.log('将错误记录到日志文件中')
      }
      // 得到楼层的数据
      try {
        const res = await request('/floordata')
        this.floorList = res.data.data
      } catch (err) {
        console.log('将错误记录到日志文件中')
      }
    }
  },
  mounted() {
    // ---------------------------- 4.0 版本 ------------------------------
    this.getData()
    // ---------------------------- 4.0 版本 ------------------------------
    // ---------------------------- 3.0 版本 ------------------------------
    // request('/swiperdata')
    //   .then( res => {
    //     this.imgList = res.data.data
    //     return request('/catitems')
    //   }).then(res => {
    //     this.cateList = res.data.data
    //     return request('/floordata')
    //   }).then(res => {
    //     this.floorList = res.data.data
    //   })
    // ---------------------------- 3.0 版本 ------------------------------
    // ---------------------------- 2.0 版本 ------------------------------
    // request('/swiperdata')
    //   .then(res => {
    //     this.imgList = res.data.data
    //     request('/catitems')
    //       .then( res => {
    //         this.cateList = res.data.data
    //         request('/floordata')
    //           .then( res => {
    //             this.floorList = res.data.data
    //           })
    //       })
    //   })
    // ---------------------------- 2.0 版本 ------------------------------
    // ---------------------------- 1.0 版本 ------------------------------
    // // 请求轮播图的数据
    // wx.request({
    //   url: '/swiperdata',
    //   method: 'GET',
    //   success: res => {
    //     // 箭头函数中的 this 指向的是外层(上一级作用域中的 this)
    //     this.imgList = res.data.data
    //   }
    // })
    // // 请求分类选项的数据
    // wx.request({
    //   url: '/catitems',
    //   method: 'GET',
    //   success: res => {
    //     this.cateList = res.data.data
    //   }
    // })
    // // 请求楼层数据
    // wx.request({
    //   url: '/floordata',
    //   method: 'GET',
    //   success: res => {
    //     this.floorList = res.data.data
    //     console.log(this.floorList)
    //   }
    // })
    // ---------------------------- 1.0 版本 ------------------------------
  },

相关文章

  • 微信小程序-ajax的使用和封装

    微信小程序的ajax使用方法: ajax 函数封装 在我们做项目的时候,为了方便复用,需要封装ajax函数方便随时...

  • 小程序封装ajax及使用方法

    微信小程序提供了网络请求方法,但是用起来不太方便,就自己封装了下。 封装源码 引用 同时请求多个ajax的便捷方法

  • 小程序ajax封装

    前言 微信小程序提供了网络请求方法,但是用起来不太方便,就自己封装了下。 封装源码 引用 优化提示 以上只是简易版...

  • Golang操作RabbitMQ

    程序封装 使用方法

  • ajax的封装

    前两天,我们研究了Ajax的基本原理和使用方法,那么今天我们在此基础上简单的封装一个ajax。一、ajax怎么封装...

  • 总结js常用函数和常用技巧

    学习过程中总结的干货,包括常用函数、常用js技巧、常用正则表达式等。 Ajax封装 使用方法: 后台响应Ajax ...

  • 封装wx小程序的ajax

    改造wx的ajax为promise,方便使用async和await语法

  • js原生ajax

    Ajax及封装Ajax详解参考传送门:https://blog.csdn.net/c__dreamer/artic...

  • ajax函数封装

    ajax函数封装 封装一个ajax

  • 记一次Promise对小程序网络请求的简单封装

    尽管小程序的网络请求已经算是封装好的(类似通过函数对ajax的一层封装),但是当同时涉及多个请求时还是会出现多个回...

网友评论

      本文标题:小程序封装ajax及使用方法

      本文链接:https://www.haomeiwen.com/subject/ktxzlctx.html