Fork me on GitHub

小程序简单封装request请求

es6 封装request请求

 

为了使代码更精简,便于理解和维护,使用 new Promise方法对request请求进行封装

new Promise(resolve, reject) 含有两个参数

resolve :成功时的调用

reject:失败时的调用

app.js中封装request请求

App({
  onLaunch: function(options) {
  },
  globalData: {
    localUrl: "https://www.baidu.com",
  },
  request(api, params, method) {
    return new Promise((resolve, reject) => {
      wx.request({
        url: this.globalData.localDoctorUrl + api,
        data: params,
        header: {
          'content-type': 'application/x-www-form-urlencoded',
          'csrf-csrf': 'csrf-csrf',
        },
        method: method ? method : 'get',
        success: (res) => {
          resolve(res)
        },
        fail: (err) => {
          wx.showToast({
            title: err,
            icon: 'none'
          });
          reject("请求失败")
        }
      })
    })
  },
})

 

在其他需要用到请求的页面直接引用

 
const app=getApp();
 
//request请求
 
app.request("接口地址","参数","post/get").then(res=>{
 
//请求成功的处理
 
}).catch(err=>{
 
//请求失败的处理
 
})

 

======================================================================================================================================================

 或者,直接引用request.js

const host = 'http://........';

function request(api, params, method, resolve, reject) {
    wx.request({
      url: host + api,
      data: params,
      header: {
        "content-type": "application/json;charset=UTF-8",
      },
      method: method ? method : 'get',
      success: function (res) {
        resolve(res);
      },
      fail: function (err) {
        reject(err);
      },
    })
}
module.exports.request = request;

在index.js中使用

import {
  request
} from '../../config/request.js'; //request路径
const api = "/...........";

getRequest() {
      request(api, params, method, res => {
          console.log(res)
          //请求成功的操作
           wx.showToast({
              title: "请求成功",
              icon: 'success'
            })
        }, err => {
          console.log(err)
         //请求失败操作
          wx.showToast({
            title: '发表请求失败',
            icon: 'none'
          })
      })
} 

 

posted @ 2019-10-25 14:08  ssh__F  阅读(672)  评论(0编辑  收藏  举报