• 小程序wx.request请求的简单封装


    1、api.js

    const baseUrl = 'https://api.it120.cc';
    
    const http = ({ url = '', param = {}, ...other } = {}) => {
        wx.showLoading({
            title: '请求中,请耐心等待..'
        });
        let timeStart = Date.now();
        return new Promise((resolve, reject) => {
            wx.request({
                url: getUrl(url),
                data: param,
                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)
                    }
                }
            })
        })
    }
    
    const getUrl = (url) => {
        if (url.indexOf('://') == -1) {
            url = baseUrl + url;
        }
        return url
    }
    
    // get方法
    const _get = (url, param = {}) => {
        return http({
            url,
            param
        })
    }
    
    const _post = (url, param = {}) => {
        return http({
            url,
            param,
            method: 'post'
        })
    }
    
    const _put = (url, param = {}) => {
        return http({
            url,
            param,
            method: 'put'
        })
    }
    
    const _delete = (url, param = {}) => {
        return http({
            url,
            param,
            method: 'put'
        })
    }
    module.exports = {
        baseUrl,
        _get,
        _post,
        _put,
        _delete
    }

    2、页面调用

    const api = require('../../utils/api.js')
     
    // 单个请求
    api.get('list').then(res => {
     console.log(res)
    }).catch(e => {
     console.log(e)
    })
     
    // 一个页面多个请求
    Promise.all([
     api.get('list'),
     api.get(`detail/${id}`)
    ]).then(result => {
     console.log(result)
    }).catch(e => {
     console.log(e)
    })
    与尘埃中开出花朵。
  • 相关阅读:
    css控制textarea固定大小不可拖动
    js绑定回车事件
    这一周的收获与总结_BP
    20140824
    【转】Hadooop学习笔记
    【转】CUDA优化小记录
    【转】CUDA程序优化要点
    cublas 矩阵相乘API详解
    CUDA 矩阵相乘完整代码
    CUDA 矩阵相乘
  • 原文地址:https://www.cnblogs.com/congfeicong/p/11235046.html
Copyright © 2020-2023  润新知