接口封装 ,新建/api/request.js
import Taro from "@tarojs/taro"; // api请求封装 const htttRequest = function (url: string, paramet: object, method: any, showToast: Boolean) { // 获取token const token = Taro.getStorageSync('Info') if (showToast) { Taro.showLoading({ title: '加载中', }) } return new Promise<{}>((resolve, reject) => { Taro.request({ url: BASE_URL + url, data: paramet, method: method, header: { 'content-type': 'application/json', 'Authorization': token.accessToken ? token.accessToken : '', } }).then((res) => { Taro.hideLoading() switch (res.data.statusCode) { case 200: return resolve(res.data) case 10014: // token校验失败 Taro.navigateTo({ url: '/pages/login/index' }) Taro.clearStorageSync() return reject(res.data) case 10002: // 缺少商户信息 Taro.navigateTo({ url: '/pages/login/index' }) return reject(res.data) default: setTimeout(() => { Taro.showToast({ title: res.data.comments, icon: 'none', }) }, 500); } }).catch(err => { Taro.showToast({ title: '小程序数据请求失败', icon: 'none' }) return reject(err) }) }) } export default htttRequest
2. 接口列表
import htttRequest from './request' // 查询记录 const getWriteOffPage = (param) => htttRequest(`${seller}/pageQuery${formatGetUri(param)}`, {}, 'GET', true) export default { getWriteOffPage }
3. 接口调用
import api from '../../api/index' import Taro, {useEffect } from "@tarojs/taro"; function WriteOff() { useEffect(() => { getDateInfo() }, []) const getDateInfo = () => { api.getWriteOffPage({ }).then((res: any) => { console.log('获得数据') }) } }
来源:https://www.cnblogs.com/gqx-html/p/12553415.html