封装原生的微信小程序ajax请求

使用promise封装原生的微信小程序ajax请求

这里需要注意的一点是:在进行数据请求的时候,一定要在微信开发者工具详情里面

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-HCjBuTUy-1593522567511)(C:\Users\l\AppData\Roaming\Typora\typora-user-images\image-20200630205906404.png)]

这里面一定要勾选上,不然会报错,数据请求不到

原生自己封装

/**
 * 使用promise封装原生的微信小程序ajax请求
 * @param {string} url            请求路径
 * @param {object} params         请求参数
 * @param {string} methods        请求类型
 * @param {object} header         请求头
 */
const app = getApp()
const hosturl = app.globalData.host

module.exports = (url, params = {}, methods = "GET", header = {}) => {
  return new Promise((resolve, reject) => {
    wx.request({
      url:hostrul+url //仅为示例,并非真实的接口地址
      methods,
      data: params,
      success: resolve,
      fail: reject
    })
  })
}

使用:

const fetch = require("../../utils/fetch")

网上封装的比较好的原生微信小程序ajax请求

const app = getApp()


const request = (url, options) => {
  return new Promise((resolve, reject) => {
    wx.request({
      url: `${app.globalData.host}${url}`,
      method: options.method,
      data: options.method === 'GET' ? options.data : JSON.stringify(options.data),
      header: {
        'Content-Type': 'application/json; charset=UTF-8',
        'x-token': 'x-token'  // 看自己是否需要
      },
      success(request) {
        if (request.data.code === 2000) {
          resolve(request.data)
        } else {
          reject(request.data)
        }
      },
      fail(error) {
        reject(error.data)
      }
    })
  })
}

const get = (url, options = {}) => {
  return request(url, { method: 'GET', data: options })
}

const post = (url, options) => {
  return request(url, { method: 'POST', data: options })
}

const put = (url, options) => {
  return request(url, { method: 'PUT', data: options })
}

// 不能声明DELETE(关键字)
const remove = (url, options) => {
  return request(url, { method: 'DELETE', data: options })
}

module.exports = {
  get,
  post,
  put,
  remove
}

封装flyio

步骤:

1.下载:(一开始一定要初始化一下,让项目变成一个node项目)

npm     init    -y
npm   i   flyio   -S    (下载flyio的包)

2.下载下来之后,把包单独拎出来,不要放在nodemodel里面

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-KoTVDnCp-1593522567515)(C:\Users\l\AppData\Roaming\Typora\typora-user-images\image-20200630203813241.png)]

3.封装:

// 1. 引入flyio  
import Fly from './flyio/dist/npm/wx'
// 2. 实例化
const fly = new Fly()
const host = getApp().globalData.host
// 添加请求拦截器
fly.interceptors.request.use(
  (request) => {

    wx.showLoading({
      title: '加载中',
      mask: true
    })
    // console.log(request)
    // request.headers["X-Tag"] = "flyio";
    // request.headers['content-type']= 'application/json';
    request.headers = {
      'X-Tag': 'flyio',
      'content-type': 'application/json'
    }

    let authParams = {
      // 公共参数
      'categoryType': 'SaleGoodsType@sim',
      'streamNo': 'wxapp153570682909641893',
      'reqSource': 'MALL_H5',
      'appid': 'string',
      'timestamp': new Date().getTime(),
      'sign': 'string'
    }

    request.body && Object.keys(request.body).forEach((val) => {
      if (request.body[val] === '') {
        delete request.body[val]
      };
    })
    request.body = {
      ...request.body,
      ...authParams
    }
    return request
  })

// 添加响应拦截器
fly.interceptors.response.use((response) => {
  wx.hideLoading()
  return response.data// 请求成功之后将返回值返回
},
  (err) => {
    // 请求出错,根据返回状态码判断出错原因
    console.log(err)
    wx.hideLoading()
    if (err) {
      return '请求失败'
    };
  }
)

// 3. 配置根路径
fly.config.baseURL = host

export default fly

4.使用

import api from "../../api/index"    //引入
async getSlides() {      //进行数据请求
    const res = await api.get("/slides")
    this.setData({
      slides: res
    })
  },
  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值