微信小程序-封装请求

在开发中,前端时常遇到请求接口返回数据,但是每一次请求接口用到的原生方法实在是太过于麻烦,所以就想封装一个微信小程序请求接口的方法(一切为了偷懒...)

  在微信小程序种,请求接口的方法只有wx.request方法(内部参数贼多,麻烦的一批,一切为了偷懒...)

  

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

  以上是微信开发者平台文档给出的请求方式,

  用起来贼麻烦...

  创建一个新文件夹来放置请求方法,(一般这类方法好像都放在utils文件夹下面)

  (开启封装模式...)

  api.js

  

var base="https://123.123.123.1:8080/"function postData(url,query,callback,error){ wx.request({ url:base + url, data:query, method:‘post‘, header:{ ‘content-type‘:‘application/json;charset=UTF-8‘ }, success(res){ // 此处随意发挥 callback(res) }, fail(){ error() }, }) }function getData(url,params,callback,error){ wx.request({ url:base + url, data:params, method:‘get‘, header:{ ‘content-type‘:‘application/json‘ } , success(res){ callback(res) }, fail(){ error() } }) } module.exports.postData = postData;module.exports.getData = getData;

  js封装完毕(只封装了常用的两种方式,其他方式,emmm,反正我没用到,嘿嘿)

微信小程序-封装请求

  调用时只需要引入就可以了:

   import {postData,getData} from ‘utils/api.js‘

   或

   var req = require(‘utils/api.js‘)

   通过 req.postData()或req.getData()使用

   (当然,第一种是我在vue常用的一种方式,咱也不知道到底能不能这样用,我还没有开发过小程序一类的东西,所以一切都是臆想)

   然后就可以使用了(应该可以...嗯..)

本人对小程序接触不深,也没有上手过,一切为了偷懒,谁能确定我以后用不用的到...

相关文章