小程序请求封装http.js

2020-04-10  本文已影响0人  下班再说

http.js

const app = getApp();// 接口地址(测试需改本页接口地址和app.js的图片地址)

const api_url = 'https://api.sea-1st.com/';//正式

// 错误提示

const tips = {

    1: '抱歉,出现了一个未知错误',

    401: 'Token过期或无效',

    404: '服务器被偷了',

    405: '请求错误',

    500: '服务器错误',

    501: '请求未被支持'

}

class HTTP {

// 网络请求函数

    request(params) {

        if (!params.method) {

            params.method = 'GET'

        }

        wx.showLoading({

            title: '正在请求',

            mask:true,

        })

        wx.request({

            url: api_url + params.url,

            method: params.method,

            data: params.data,

            header: {

                'content-type': 'application/x-www-form-urlencoded',

                'Authorization': app.globalData.token

            },

            success: (res) => {   

                 let statusCode = res.statusCode.toString();

                if (statusCode=='200') {

                    // 回调函数

                    params.success(res.data);

                    // console.log(res.data);

                } else {   

                    if (statusCode=='401'){

                        app.login_out();

                        app.goLogin('index');

                    }

                    this._show_error(statusCode);

                }

            },

            fail: () => {

                this._show_error(1);

            },

            complete: () => {

                wx.hideLoading()

            }

        })

    }

    // 错误处理函数

    _show_error(error_code) {

        if (!tips[error_code]) {

            error_code = 1

        }

        wx.showToast({

            title: tips[error_code],

            icon: 'none',

            duration: 2000

        })

    }

}

export {

    HTTP

}

// 调用模板-仅适用该程序接口数据返回形式

// http.request({

    // url: '',

    // data: { // },

    // method: 'POST',

    // success: (res) => {

        // var info = res;

        // app.tip(info.msg);

        // if (info.code == 0) {

        // }

    // }

// })

调用

import { HTTP } from '../../utils/http.js';

let http = new HTTP();

上一篇 下一篇

猜你喜欢

热点阅读