微信小程序之 wx-request封装 全局使用

200 阅读1分钟

1. 在项目utils文件夹内新建 request.js 文件,并进行配

var baseurl = "http://127.0.0.1:3000" // 域名接口地址
const request = (url, options) => {
// 当发起请求的时候,界面出现“数据加载中...”的Loading界面
    wx.showLoading({
        title: '数据加载中...',
        mask: true
    })
    return new Promise((resolve, reject) => {
        wx.request({
            url: baseurl + url, //请求的接口地址
            timeout: 5000, // 请求超时时间
            method: options.method, //配置method方法
            //如果是GET,GET自动让数据成为query String,其他方法需要让options.data转化为字符串
            data: options.method === 'GET' ? options.data : JSON.stringify(options.data),
            header: {
                'Content-Type': 'application/json; charset=UTF-8',
                // token值等 这里的值根据后端需要传参
                'Authorization': wx.getStorageSync('AuthorizationToken')
            }, 
            success(res) { //监听成功后的操作
                if (res.data.code === 0) {
                    resolve(res.data)
                } else {
                    wx.showToast({
                        title: res.data.msg,
                        icon: 'none'
                    })
                }
            },
            fail(error) { //返回失败可以根据需要设置 - reject()
                // reject()
                wx.showToast({
                    title: '接口走丢了~',
                    icon: 'none'
                })
            },
            complete: () => {
                // 请求完成关闭Loading
                wx.hideLoading();
            }
       })
    })
}

//封装get方法
const get = (url, options = {}) => {
    return request(url, {
        method: 'GET',
        data: options
    })
}

//封装post方法
const post = (url, options = {}) => {
    return request(url, {
        method: 'POST',
        data: options
    })
}

//封装put方法
const put = (url, options) => {
    return request(url, {
        method: 'PUT',
        data: options
    })
}

//封装remove方法,DELETE关键字不能声明
const remove = (url, options = {}) => {
    return request(url, {
        method: 'DELETE',
        data: options
    })
}

module.exports = {
    get,
    post,
    put,
    remove
}

2. 在 app.js 中引用声明 request.js 来做到全局使用

import $http from '/utils/request.js'
// 或者
// const $http = require('./utils/request.js')

App({
  //request请求
  $http
})

3.页面内实现请求 index.js

const app = getApp()
Page({
  onLoad(options){
    let params = {}
    app.$http.get('/api/client/getAllArticle', params).then(res =>{
      console.log(res)
    }).catch(err => {
      console.log(err)
    })
  }
})