Taro request 请求封装
在根目录下创建service文件夹
再创建 baseUrl文件 写入请求地址
const getBaseUrl = (url) => { let BASE_URL = ''; if (process.env.NODE_ENV === 'development') { //开发环境 - 根据请求不同返回不同的BASE_URL BASE_URL = 'https://*********' } else { // 生产环境 BASE_URL = 'https://*********' } return BASE_URL } export default getBaseUrl;
创建config.js文件写入常用状态码
export const HTTP_STATUS = { SUCCESS: 200, CREATED: 201, ACCEPTED: 202, CLIENT_ERROR: 400, AUTHENTICATE: 401, FORBIDDEN: 403, NOT_FOUND: 404, SERVER_ERROR: 500, BAD_GATEWAY: 502, SERVICE_UNAVAILABLE: 503, GATEWAY_TIMEOUT: 504 }
创建http文件写入逻辑
import Taro from '@tarojs/taro' import getBaseUrl from './baseUrl' import interceptors from './interceptors' interceptors.forEach(interceptorItem => Taro.addInterceptor(interceptorItem)) class httpRequest { baseOptions(params, method = "GET") { let { url, data,param } = params; const BASE_URL = getBaseUrl(url); // let contentType = "application/x-www-form-urlencoded"; let contentType = "application/json;charset=UTF-8"; contentType = params.contentType || contentType; const option = { url: BASE_URL + url, //地址 data: data, //传参 method: method, //请求方式 timeout:50000, // 超时时间 header: { //请求头 'content-type': contentType, 'Authorization':Taro.getStorageSync('Authorization') } }; return Taro.request(option); } get(url, data = "",param) { let option = { url, data,param }; return this.baseOptions(option); } post(url, data,param, contentType) { let params = { url, data,param, contentType }; return this.baseOptions(params, "POST"); } put(url, data = "") { let option = { url, data }; return this.baseOptions(option, "PUT"); } delete(url, data = "") { let option = { url, data }; return this.baseOptions(option, "DELETE"); } } export default new httpRequest()
再创建interceptors文件 写入异常显示逻辑
import Taro from "@tarojs/taro" import { pageToLogin } from "./utils" import { HTTP_STATUS } from './config' const customInterceptor = (chain) => { const requestParams = chain.requestParams Taro.showLoading({ title: '加载中', }) return chain.proceed(requestParams).then(res => { Taro.hideLoading() // 只要请求成功,不管返回什么状态码,都走这个回调 if (res.statusCode === HTTP_STATUS.NOT_FOUND) { return Promise.reject({ desc: '请求资源不存在' }) } else if (res.statusCode === HTTP_STATUS.BAD_GATEWAY) { return Promise.reject({ desc: "服务端出现了问题" }) } else if (res.statusCode === HTTP_STATUS.FORBIDDEN) { Taro.setStorageSync("Authorization", "") pageToLogin() // TODO 根据自身业务修改 return Promise.reject({ desc: "没有权限访问" }); } else if (res.statusCode === HTTP_STATUS.AUTHENTICATE) { Taro.setStorageSync("Authorization", "") pageToLogin() return Promise.reject({ desc: "需要鉴权" }) } else if (res.statusCode === HTTP_STATUS.SERVER_ERROR) { return Promise.reject({ desc: "服务器错误" }); } else if (res.statusCode === HTTP_STATUS.SUCCESS) { if (res.data.code === 0) { return res.data } else if (res.data.code == '-100') { //非法登录 pageToLogin() } else { return Promise.reject(res.data) } } }).catch(error=> { Taro.hideLoading() console.error(error) return Promise.reject(error) }) } // Taro 提供了两个内置拦截器 // logInterceptor - 用于打印请求的相关信息 // timeoutInterceptor - 在请求超时时抛出错误。 // const interceptors = [customInterceptor, Taro.interceptors.logInterceptor] const interceptors = [customInterceptor] export default interceptors
创建utils文件 写入处理异常状态方法
import Taro from "@tarojs/taro"; /** * @description 获取当前页url */ export const getCurrentPageUrl = () => { let pages = Taro.getCurrentPages() let currentPage = pages[pages.length - 1] let url = currentPage.route return url } export const pageToLogin = () => { let path = getCurrentPageUrl() Taro.clearStorage() if (!path.includes('login')) { Taro.reLaunch({ url: "/pages/login/login" }); } }
最后创建 servers文件进行api注册
import HTTPREQUEST from "./http" export const getLogin = (data) => { return HTTPREQUEST.post('/api/login/login', data) }
最后在页面引入就可以了