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

微信小程序请求封装

作者: 小李不小 | 来源:发表于2023-06-13 10:06 被阅读0次

官方给出请求方式为

详情参见这里

wx.request({
    url: "请求地址",
    method: "请求方式",
    header: {
    "content-type": "application/json", // 默认
    },
    success: function (res) {}, // 成功调用
    fail: function(res){}, // 失败调用
    complete: function(res){}, // 调用结束回调函数(成功失败都执行)
});

通常项目中会有很多需要请求的接口

我们每次都需要写这些参数的话就很麻烦

那么微信小程序会不会有类似vue中axios那样的东西呢

推荐两个自己封装的请求

第一种

在小程序目录下建立 api 文件夹,并在文件夹下创建 api.js 脚本。下面开始封装 wx.request

const app = getApp()
 
const request = (url, options) => {
   return new Promise((resolve, reject) => {
       wx.request({
            // {app.globalData.host}为接口请求中的公共部分写在app.js中
           url: `${app.globalData.host}${url}`,
           method: options.method,
           data: options.method === 'GET' ? options.data : JSON.stringify(options.data),
           header: {
               'Content-Type': 'application/json; charset=UTF-8',
           },
           success(request) {
               if (request.data.code === 2000) {
                   resolve(request.data)
               } else {
                   reject(request.data)
               }
           },
           fail(error) {
               reject(error.data)
           }
       })
   })
}
 
const get = (url, options = {}) => {
   return request(url, { method: 'GET', data: options })
}
const post = (url, options) => {
   return request(url, { method: 'POST', data: options })
}
const put = (url, options) => {
   return request(url, { method: 'PUT', data: options })
}
// 不能声明DELETE(关键字)
const remove = (url, options) => {
   return request(url, { method: 'DELETE', data: options })
}
 
module.exports = {
   get,
   post,
   put,
   remove
}

app.js

//app.js
App({
  onLaunch: function () {},
  globalData: {
    host: "http://XXXX.com/",
  },
});

使用封装过后的 api

post 请求就是api.post()…,get 请求就是api.get()…

import api from '../api/api'
 
Page({
 data:{},
 onLoad: function () {
    this.getlist(); // 获取列表
 }, 
 getlist() {
    // 改变this指向
    let that = this;
    api.post('/api/admin/index', {data: ''})
    .then(res => {
    console.log(res)
    })
    .catch(err => {
    wx.showToast({
        title: err.message,
    })
})
  },
)}
 

第二种

const GET = "GET";
const POST = "POST";
const PUT = "PUT";
const FORM = "FORM";
const DELETE = "DELETE";
 
const baseURL = "http://XXXXXX.com/";
 
let header = { "content-type": "application/json" };
 
function request(method, url, data) {
  return new Promise(function (resolve, reject) {
    wx.request({
      url: baseURL + url,
      method: method,
      // get请求直接传就可以了,post请求JSON.stringify(data)一下
      data: method === POST ? JSON.stringify(data) : data,
      // dataType为官方给的方法,返回的数据为 JSON,返回后会对返回的数据进行一次 JSON.parse
      // dataType: "JSON",
      header: header,
      success(res) {
        //请求成功返回数据
        resolve(res);
      },
      fail(err) {
        //请求失败
        reject(err);
        console.log(err);
        wx.showToast({
          icon: "none",
          mask: true,
          title: "服务器出错了,请稍后再试",
        });
      },
    });
  });
}
 
 
 
// 请求不同的接口
const API = {
  getList: () => request(GET, "api/commodity/showList"), //获取商品列表
};
module.exports = {
  API,
};

页面中使用

const api = require("../../utils/http").API;
Page({
 data:{},
 onLoad: function () {
    this.getlist(); // 获取列表
 }, 
 getlist() {
    // 改变this指向
    let that = this;
    api.getshopList()
      .then((res) => {
        //请求成功
        that.setData({ list: res.data.data });
      })
      .catch((err) => {
        //请求失败
      });
  },
)}

相关文章

网友评论

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

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