相信大家在做微信小程序的時候會有很多地方需要調用接口,就和pc以及手機端一樣,多個頁面多次調用會有很多狀態,那為了節省大家的開發時間就會需要給請求的接口做一些簡單封裝,便於開發,在這里我用了兩個js,一個js封裝的是方法名,另外一個是接口名,統一管理
下面這個是統一的接口方法封裝
const baseURL = "接口名"; const request = params => { const token = wx.getStorageSync("token").token; return new Promise((resolve, reject) => { wx.showLoading(); wx.request({ url: baseURL + params.url, data: params.data, method: params.method, header: { 'content-type': 'application/x-www-form-urlencoded;charset=utf-8', token: token }, success(res) { const pages = getCurrentPages(); // const app = getApp(); if (res.statusCode === 200) { if (res.data.code === 200) { resolve(res.data); } else if (res.data.code === 401) { wx.navigateTo({ url: '/pages/login/index', }) } else { if (res.data.code == 1104) { wx.clearStorageSync() wx.redirectTo({ url: '/pages/login/index', }) } else { reject(res.data); } } } }, fail(err) { reject(err); }, complete() { wx.hideLoading(); } }); }); }; const _upload = (filePath, type) => { const token = wx.getStorageSync("token").access_token; return new Promise((resolve, reject) => { wx.showLoading(); wx.uploadFile({ url: baseURL + "upload_file", //僅為示例,非真實的接口地址 filePath, name: "file", header: { authorization: token ? "Bearer " + token : undefined }, formData: { type }, success(res) { resolve(JSON.parse(res.data)); }, fail(err) { reject(err); }, complete() { wx.hideLoading(); } }); }); }; const _get = (url, data) => { return request({ url, data, method: "GET" }); }; const _post = (url, data) => { return request({ url, data, method: "POST" }); }; const _put = (url, data) => { return request({ url, data, method: "PUT" }); }; const _delete = (url, data) => { return request({ url, data, method: "DELETE" }); }; module.exports = { baseURL, _get, _post, _put, _delete, _upload };
下面這個是統一的接口管理
import { _get, _post, _put, _delete, _upload } from "./request"; // 圖片上傳 const getUploadImg = data => { return _post("接口名", data); }; module.exports = { getUploadImg };
封裝的比較簡單粗暴,不過通俗易懂
使用的時候直接在頁面引入就可以