• 小程序简单封装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'
              })
          })
    } 
  • 相关阅读:
    csu 1604 SunnyPig (bfs)
    openjudge 大师兄,师傅被妖怪抓走啦
    poj 3264 线段树 求区间最大最小值
    bzoj 1012 维护一个单调数列
    poj 1840 暴力+标记
    最短路径(Dijkstra实现)
    最小生成树(Kruskal实现)
    最小生成树(Prim实现)
    拓扑排序(Kahn实现)
    拓扑排序(DFS实现)
  • 原文地址:https://www.cnblogs.com/tt-ff/p/11737719.html
Copyright © 2020-2023  润新知