微信小程序开发--网络请求封装

171 阅读1分钟

config/baseUrl.js

export const BASE_URL = 'https://服务器地址';

tips:

image.png

  • 设置->代理设置->"不使用任何代理"

image.png

utils/http.js


import { BASE_URL } from '../config/baseUrl'

const initOptions = {
  loading:true, 
  modal:false, 
  toastTime:2000, 
  method:'GET',
  data:{},
  header:{},
  loadingText:'加载中',
  timeout:50000
}
function request(reqBody) {
  const options = Object.assign(reqBody, initOptions)
  console.log("request",options);
  console.log("url",BASE_URL + options.url);
  if (options.loading) {
		wx.showLoading({
			title: "加载中",
			mask: true,
		});
	}
    return new Promise((resolve, reject) => {
      console.log("===========request==============");
      const header = {
        'Content-Type': 'application/json;charset=UTF-8',
        // 'token': wx.getStorageSync('token'), //获取保存的token
        Authorization:'Bearer xxxxxx',
        ...options.header // 可以传入额外的请求头参数
      }
      wx.request({
        url: BASE_URL + options.url,
        data:options.data,
        method:options.method,
        timeout: options.timeout,
        //添加请求头
        header,
        //请求成功
        success: (res)=> {
          if (res.statusCode == 200) {
            resolve(res);
          } else if (res.statusCode == 401) {//授权失效
            reject("登录已过期");
            jumpToLogin();//跳转到登录页
          } else {
            //请求失败
		if (options.needModal) {
                    wx.showModal({
                        content: res.data.message || '请求失败,请重新尝试',
			showCancel: false,
			})
		} else {
                    wx.showToast({
                        icon: 'none',
                        duration: options.toastTime,
                        title: res.statusCode !== 200 ?'服务器无响应,请联系管理员' : (res.data.message || '请求失败,请重新尝试'),
                        })
                   }
            reject(res)
            return
          }
        },
        fail: function(err) {
          //服务器连接异常
          wx.showToast({
            icon: 'none',
            title: '服务器错误 或网络中断,请重新尝试',
          })
          reject(err);
        },
        complete: function() {
          if (options.loading) {
            wx.hideLoading()
          }
        }
      })
    });
  }
 
  //跳转到登录页
  function jumpToLogin(){
    wx.reLaunch({
      url: '/pages/login/login',
    })
  }

  export default request

页面中使用

  • page/myPage/index.wxml

<van-cell icon="gift-o" title="我收到的礼物" is-link bindtap="handleTap"/>
//bindtap 绑定事件
  • page/myPage/index.js

import request from '../../utils/http'

Page({

  data: {
    list:[]
  },

async getList(){
  try{
    const res = await request({
     url:'/system/dict/data/type/cu_industry',
    })
     console.log("res",res);
     this.setData({
       list:res.data
     })
   }catch(err){}

  //页面绑定的事件
  handleTap(){
    this.getList()
  }
  
})