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

网络请求小程序提供了wx.request

// 官方例子
wx.request({
  url: 'test.php', //仅为示例,并非真实的接口地址
  data: {
     x: '' ,
     y: ''
  },
  header: {
      'content-type': 'application/json' // 默认值
  },
  success: function(res) {
    console.log(res.data)
  }
})

小程序支持ES6,那么就应该支持Promise 了,下面是我封装的请求

Promise封装
const baseUrl = 'https://csdn.net';

export const http = ({ url = '', param = {}, method="get",...other } = {}) => {
    wx.showLoading({
        title: '请求中,请耐心等待..'
    });
    let timeStart = Date.now();
    return new Promise((resolve, reject) => {
        wx.request({
            url: getUrl(url),
            data: param,
            methods,
            header: {
                'content-type': 'application/json' // 默认值 ,另一种是 "content-type": "application/x-www-form-urlencoded"
            },
            ...other,
            complete: (res) => {
                wx.hideLoading();
                console.log(`耗时${Date.now() - timeStart}`);
                if (res.statusCode >= 200 && res.statusCode < 300) {
                    resolve(res.data)
                } else {
                    reject(res)
                }
            }
        })
    })
}

我这方便以后好维护 创建了一个api文件夹 每个页面每个模块再api下面创建一个文件夹
比如:在这里插入图片描述

在我们创建好的index.js下面 引入我们封装好的http.js

import http from '@/utils/http.js'

export function editApi(query) {
  return http({
    url: '/iwopbase/fenceinfo',
    method: 'put',
    param : query
  })
}

如果要在页面上用 我们就可以引入对应的接口

import {editApi}   form "@/api/ccc/index.js";
let params = {
id:321,
}
editApi(params).then(res=>{

})

留下你的赞吧

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值