小程序接口请求封装方法

1、配置app.js
在这里插入图片描述

App({   
  onLaunch: function() {   
  },  
  globalData: {       
      userInfo: null,       
      loginCode: null,       
      version: '1.0.0',       
      baseUrl:'https://www.test.com'  //根据自己的请求地址配置
  }
})

2、封装request

const app = getApp();
const baseURL = app.globalData.baseUrl; //引用baseUrl
const Request = (options) => {
	return new Promise((resolve,reject) => {
		wx.request({
			url: baseURL + options.url || '',
			data: options.data || {},
			method: options.method || 'POST',
			header: { 'Authorization': "" }, //设置请求头
			responseType: options.responseType || "text", 
			timeout: 15000,
			success(res) {
				resolve(res.data);
			},
			fail(res) {
				reject(res);
			}
		})
	})
};

module.exports = {
	Request
};

3、封装API

const request = require('../api/request'); //引用封装的request

const HTTP = {
  systemDetails(url) {
    return request.Request({
      url: '/test/system/details'+url, 
      method: 'get' 
    })
  },
  systemList(data,url) {
    return request.Request({
      url: '/test/system/list'+url, 
      method: 'post', 
      data:data 
    })
  },
}

module.exports = HTTP;

4、使用方法

import HTTP from "../../api/api";  //引用封装的api
const app = getApp()

Page({
  data: {
    pageNum:1,
    pageSize:10,
    info: {},
    list:[],
  },
  // 接口未封装示例
  test() {
    var that = this
    wx.request({
      url: 'https://www.test.com/test/system/details',
      // data: {},
      method: 'GET',
      header: {
        'Authorization': '' // 默认值
      },
      success: function (res) {
      	console.log(res)
        that.setData({ info: res.data.data })
      }
    })
  },
  // 接口已封装示例(get)
  systemDetails() {
    var that = this
    HTTP.systemDetails(`?pageNum=${that.data.pageNum}&pageSize=${that.data.pageSize}`)
    .then(res => {
      console.log(res)
      that.setData({ info: res.data }) //渲染data
    });
  },
  //接口已封装示例(post)
  systemList() {
    var that = this
    //这里传了两个参,可根据需要修改,不传则都为空
    HTTP.systemList({
      "id": 1,
      "user": 'zhangsan'
    },`?pageNum=${that.data.pageNum}&pageSize=${that.data.pageSize}`) 
    .then(res => {
      console.log(res)
       that.setData({ list: res.data }) //渲染data
    });
  },
  //获取当前行id示例
  onItemClick(event) {
    console.log(event.currentTarget.dataset.postidIdex) //获取id
    let postidIdex = event.currentTarget.dataset.postidIdex
    //页面跳转
    tt.navigateTo({
      url: `/pages/details/details?postidIdex=${postidIdex}`, 
      //demo示例,一般路径形式:/pages/detail/detail?key=${value}
    });
  },
  //页面加载请求
  onLoad: function () {
    this.test()
    this.systemDetails()
    this.systemList()
  },
})

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值