小程序wx.request封装

具体的封装可以参考写的文章小程序获取定位
文件夹位置如下:

image

因为平时ajax请求的url一般都是固定的,所以可以新建一个页面用const定义常量统一放在一个页面中。

下面是封装函数,按照之前上面文章的思路:

//将常用的变量用const存储起来
export const TENCENTMAPURL = 'https://apis.map.qq.com/ws/geocoder/v1/'
export const TENCENTMAPKEY = 你的地图key
// 将地址常量保存命名后期拼接使用
export const LOCALHOST = 'http://localhost:8888/'
//引入外部常量
import {
  TENCENTMAPURL,
  TENCENTMAPKEY,
  LOCALHOST
} from '../utils/const.js'//注意相对路径,不要引用错了

//使用promise时,需要return,因为后面的then 需要调用return的值
export function $get(url, data) {
  return request("GET", url, data)
}
export function $post(url, data) {
  return request("POST", url, data)
}

function request(method, url, data) {
  return new Promise((resolve, rejected) => {
  //未获取成功之前显示加载中
   wx.showLoading({
    title: '加载中...',
  })
    wx.request({
      method,
      //url是拼接的,因为一般地址的前半部分是一样的,如果请求的是其他网页的话,用starsWith判断开头来决定是否要拼接,如下是一个三元表达式的判断
      url: url.startsWith('https://') ? url : LOCALHOST + url,
      data,
      success: (res) => {
        resolve(res.data)
      },
      fail: (res) => {
        rejected(res)
      },
      //当获取完成结束loading状态
      complete:(res)=>{
        wx.hideLoading()
      }
    })
  })
}

调用

$get('list').then(res=>{
      console.log(res)
    })

你可能感兴趣的:(小程序wx.request封装)