码迷,mamicode.com
首页 > 微信 > 详细

小程序请求封装

时间:2020-01-13 16:13:09      阅读:111      评论:0      收藏:0      [点我收藏+]

标签:load   b2c   const   使用   content   ready   fun   token   let   

创建请求文件http.js

var api_base_url = "this is  url";

export default function ({ url, data = {}, method = "GET" }) {
  return new Promise((resolve, reject) => {
    let contentType = method == ‘POST‘ ? ‘application/x-www-form-urlencoded‘ : ‘application/json‘;
    wx.request({
      url: api_base_url + url,
      method: method,
      data: data,
      header: {
        "content-type": contentType,
      },
      success: (res) => {
        const code = res.statusCode.toString();
        if (code.startsWith(‘2‘)) {
          resolve(res.data)
          console.log("success", res.data)
        } 
        else {
          reject(res.data)
          console.log("error", res.data)
        }
      },
       fail: (err) => {
        console.log("fail", err)
      }
    })
  })
}

 创建公共接口文件 api.js

import http from ‘./http.js‘

function getSuccessData(params) {
  return http({
    method: ‘GET‘,
    url: ‘url‘,
    data: params
  })
}

function postFormData(params){
  return http({
    method: ‘POST‘,
    url: ‘url‘,
    data: params
  })
}

export { getSuccessData, postFormData }

 使用

import {
  getSuccessData,
  postFormData
} from ‘../../utils/api.js‘

Page({
  data: {},
  onLoad: function(options) {
    this.getData()
  },
  //获取数据
  getData() {
    let data = {
      utoken: "utoken_e6edde9df7cb836b2ceb04b2228505c0",
      i: 170
    }
    getSuccessData(data).then(result => {
      console.log(result)
      return postFormData({id: "11"}).then((res)=>{
        console.log(res)
      })
    })
  },
  onReady: function() {},
  onShow: function() {},
  onHide: function() {},
  onUnload: function() {},
  onPullDownRefresh: function() {},
  onReachBottom: function() {},
  onShareAppMessage: function() {}
})

  

 

小程序请求封装

标签:load   b2c   const   使用   content   ready   fun   token   let   

原文地址:https://www.cnblogs.com/Glant/p/12187633.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!