微信小程序开发之网络请求封装(支持form表单)

 使用介绍

在布局js中引用 这个根据自己放的位置引用

import api from '../../utils/api.js'

form提交

 api.postF(app.globalData.addProcess + id, {
        formId: formId,
        remindTime: time[selectPositon]
      }).then(res => {
        if (!res) {
          return;
        }
        
      })

 

get请求

    api.get(app.globalData.getTimeSheetSubList + queryStartDate).then(res => {});

post请求json提交

 api.post(app.globalData.addAttention, selectThemes).then(res => {
      if (res) {
        
      }
    })

工具类Api

var isLogin = false;
const request = (url, options) => {
  wx.showNavigationBarLoading()
  return new Promise((resolve, reject) => {
    wx.request({
      url: `${url}`,
      method: options.method,
      data: options.method === 'GET' || options.header === 'application/x-www-form-urlencoded' ? options.data : JSON.stringify(options.data),
      header: {
        'Content-Type': options.header,
        'Authorization': wx.getStorageSync('token') // 看自己是否需要
      },
      success(request) {
        wx.stopPullDownRefresh()
        let token = wx.getStorageSync('token')
        if (!token && !isLogin) {
          login();
        }
        if (request.statusCode === 200) {
          // console.error(request.data)
          resolve(request.data)
        } else {
          reject(request.data)
        }
        wx.hideNavigationBarLoading()
      },
      fail(error) {
        console.error("error---" + error)
        wx.hideNavigationBarLoading()
        reject(error.data)
      },
    })
  }).catch(function(reason) {
    console.log('catch:', reason);
    let token = wx.getStorageSync('token')
    if (reason && reason.code === 403 || !token && !isLogin) {
      login();
    }
  });
}
const login = () => {
  isLogin = true;
  wx.reLaunch({
    url: '/pages/white/white',
  })
}

const get = (url, options = {}) => {
  return request(url, {
    method: 'GET',
    data: options,
    header: 'application/json; charset=UTF-8'
  })
}

const post = (url, options) => {
  return request(url, {
    method: 'POST',
    data: options,
    header: 'application/json; charset=UTF-8'
  })
}
/**
 * post表单提交
 */
const postF = (url, options) => {
  return request(url, {
    method: 'POST',
    data: options,
    header: 'application/x-www-form-urlencoded'
  })
}
const putF = (url, options) => {
  return request(url, {
    method: 'PUT',
    data: options,
    header: 'application/x-www-form-urlencoded'
  })
}
const put = (url, options) => {
  return request(url, {
    method: 'PUT',
    data: options,
    header: 'application/json; charset=UTF-8'
  })
}

// 不能声明DELETE(关键字)
const remove = (url, options) => {
  return request(url, {
    method: 'DELETE',
    data: options,
    header: 'application/json; charset=UTF-8'
  })
}

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

有问题留言吧

猜你喜欢

转载自blog.csdn.net/weixin_39706415/article/details/98939617