美文网首页
微信小程序请求封装

微信小程序请求封装

作者: 小乌龟666 | 来源:发表于2022-11-24 17:00 被阅读0次

方式一:

1、在小程序的目录下新建一个 api 的文件夹
2:在 api 文件夹中新建一个 config.js 文件,用于存放公共的服务器地址,内容如下:
const baseUrl = 'https://www.baidu.com/';
 
export {
  baseUrl
}
3:在 api 文件夹中新建一个 request.js 文件,用于存放封装的api请求,内容如下:
import { baseUrl } from './http.js'
 
module.exports = {
/*
 * url:请求的接口地址
 * methodType:请求方式
 * data: 要传递的参数
*/
  request : function(url, methodType, data){
    let fullUrl = `${baseUrl}${url}`
    let token = wx.getStorageSync('token') ? wx.getStorageSync('token')  : ''
    wx.showLoading({ title: "加载中"  });
    return new Promise((resolve,reject)=>{
      wx.request({
        url: fullUrl,
        method:methodType,
        data,
        header: {
          'content-type': 'application/json', // 默认值
          'x-api-key': token,
        },
        success: (res) => {
          if (res.data.status == 200) {
            resolve(res.data)
          }else{
            wx.showToast({
              title: res.data.msg,
              icon:'none'
            })
            reject(res.data.message)
          }
        },
        fail: () => {
          wx.showToast({
            title: '接口请求错误',
            icon:'none'
          })
          reject('接口请求错误')
        },
        complete: () => {
          setTimeout(() => {
            wx.hideLoading()
          }, 100)
        }
      })
    })
  }
}
4:在 api 文件夹中新建一个 index.js 文件,用于存放api请求的地址,内容如下:
import { request } from './request'
 
module.exports = {
  // 获取企业列表
  getCompanyList: (data) => request('/company/getlist', 'GET', data),
}
5:在文件中使用,内容如下:
// 引入 api 下的 index 文件
const $api = require('../../api/index')
 
// 在方法中调用
 goList(){
    let data = {
      aaa: this.data.cardCur,
      bbb: this.data.notice,
    }
    $api.getCompanyList(data).then((res) => {
      console.log(res,'res');
    })
  },

方式二:

前3步是一样的,区别就是封装请求的不同

封装所有请求 api/http.js

//引入封装的reuest请求
const {
    request
} = require('./request.js')
 
//基于业务封装的接口
module.exports = {
    // 登录
    getLogin: (data) => {
        return request('/***/***/***/login', 'POST', data);
    },
    // 获取企业信息
    getCompanyList: (data) => {
        return request('/***/***/***/Company', 'GET', data);
    },
}
使用
// 引入登录接口
import {
    getLogin
} from '../../api/http.js'
 
Page({
    data: {
       username: '',
       pwd: ''
    },
 
    onLoad() {
        let params = {
            username: this.data.username,
            pwd: this.data.pwd
        }
        // 登录
        getLogin(params).then(res => {
            wx.setStorageSync('Cookie', res.cookies[0])
            wx.switchTab({
                url: '../index/index'
            })
        })
    },
 
    // 退出登录 
    handleLogOut() {
        wx.clearStorageSync()
        wx.navigateTo({
            url: '../login/login'
        })
    },
})

相关文章

网友评论

      本文标题:微信小程序请求封装

      本文链接:https://www.haomeiwen.com/subject/vorxfdtx.html