uniapp微信小程序axios庫(kù)的封裝及使用詳細(xì)教程
方式一
第一步:安裝axios及適配器
安裝依賴(lài)
需要注意使用uniapp-vue3版本時(shí)axios的版本需要0.26.0以下,建議鎖版本
npm i axios@0.26.0 axios-miniprogram-adapter && yarn add axios@0.26.0 axios-miniprogram-adapter
axios-miniprogram-adapter
這個(gè)依賴(lài)主要是適配小程序網(wǎng)絡(luò)請(qǐng)求的適配器,為了解決uniapp 適配axios請(qǐng)求,避免報(bào)adapter is not a function錯(cuò)誤
第二步:axios二次封裝
在utils文件下新建request.js文件
// axios二次封裝 // yarn add axios-adapter-uniapp import axiosAdapterUniapp from 'axios-adapter-uniapp' import { getToken } from "@/utils/auth"; import axios from "axios"; // 小程序axios適配器 import mpAdapter from "axios-miniprogram-adapter"; axios.defaults.adapter = mpAdapter; import { toast, showConfirm, tansParams } from "@/utils/common"; //根據(jù)環(huán)境變量獲取api地址 let baseURL = process.env.config[process.env.UNI_SCRIPT].VITE_BASE_API; // let evnName = process.env.config[process.env.UNI_SCRIPT] 獲取當(dāng)前處于哪個(gè)開(kāi)發(fā)環(huán)境 console.log("baseURL:", baseURL, "++++++++++++++++++++++++"); class HttpRequest { constructor() { this.baseURL = baseURL; // 從環(huán)境變量中獲取api地址 this.timeout = 300000; } mergeOptions(options) { return { baseURL, timeout: 300000, ...options, }; } request(options) { const instance = axios.create(); this.setInterceptors(instance); const opts = this.mergeOptions(options); return instance(opts); } get(url, data = {}, outHeaders = {}) { // console.log(data, "data+++++++++++++"); return this.request({ dataType: "json", method: "get", url, params: { ...data }, // get參數(shù)可以直接展開(kāi) headers: {}, }); } post(url, data = {}, outHeaders = {}) { // 請(qǐng)求體中 {} return this.request({ method: "post", url, data, // post要求必須傳入data屬性 headers: {}, }); } // 設(shè)置攔截器 setInterceptors(instance) { // 請(qǐng)求攔截器 instance.interceptors.request.use((config) => { const noLoading = config.headers["NO-LOADING"]; // 是否需要設(shè)置 token const isToken = config.headers["ISTOKEN"] || false; if (getToken() && isToken) { config.header["Authorization"] = `Bearer ${getToken()}`; } if (!noLoading) { uni.showLoading({ title: "加載中...", }); } config.headers = { ...config.headers, }; //console.log('config',config) return config; }); // 響應(yīng)攔截器 instance.interceptors.response.use( (res) => { const noLoading = res.config.headers["NO-LOADING"]; if (!noLoading) { uni.hideLoading(); } let { data } = res; // console.log("請(qǐng)求獲取data", data) if (data) { if (data.code === 200) { //console.log('data=============', data) return Promise.resolve(data); } else { showConfirm({ content: data.msg, showCancel: false, }).then((res) => { /* if (res.confirm) { store.dispatch("LogOut").then((res) => { uni.reLaunch({ url: "/pages/login" }); }); } */ }); return Promise.resolve(data); } } }, (err) => { console.log("axios報(bào)錯(cuò)", err); uni.hideLoading(); return Promise.reject(err); } ); } } export default new HttpRequest();
方式二
在request.js文件中做axios適配,不需要安裝axios-miniprogram-adapter適配插件
// axios二次封裝 import { getToken } from "@/utils/auth"; import { toast, showConfirm, tansParams } from "@/utils/common"; //映入axios相關(guān) import axios from "axios"; import settle from "axios/lib/core/settle"; import buildURL from "axios/lib/helpers/buildURL"; import buildFullPath from "axios/lib/core/buildFullPath"; //解決axios0.19.0以上版本無(wú)法請(qǐng)求問(wèn)題 //根據(jù)環(huán)境變量獲取api地址 let baseURL = process.env.config[process.env.UNI_SCRIPT].VITE_BASE_API; // let evnName = process.env.config[process.env.UNI_SCRIPT] 獲取當(dāng)前處于哪個(gè)開(kāi)發(fā)環(huán)境 console.log("baseURL:", baseURL, "++++++++++++++++++++++++"); //解決uniapp 適配axios請(qǐng)求,避免報(bào)adapter is not a function錯(cuò)誤 axios.defaults.adapter = function (config) { return new Promise((resolve, reject) => { const fullurl = buildFullPath(config.baseURL, config.url); uni.request({ method: config.method.toUpperCase(), url: buildURL(fullurl, config.params, config.paramsSerializer), header: config.headers, data: config.data, dataType: config.dataType, responseType: config.responseType, sslVerify: config.sslVerify, complete: function complete(response) { response = { data: response.data, status: response.statusCode, errMsg: response.errMsg, header: response.header, config, }; settle(resolve, reject, response); }, }); }); }; class HttpRequest { constructor() { this.baseURL = baseURL; // 從環(huán)境變量中獲取api地址 this.timeout = 300000; } // ...上面已貼出封裝方式 } export default new HttpRequest();
第三步: 創(chuàng)建接口配置js文件
在src目錄下創(chuàng)建api文件夾,目錄結(jié)構(gòu)如下圖
config文件下login.js文件內(nèi)容
export default { captchaImage: "/captchaImage" }
api文件下直接子級(jí)login.js文件內(nèi)容
import axios from '@/utils/axios' import login from './config/login' // 獲取驗(yàn)證碼 export const captchaImageGet = () => axios.get(login.captchaImage)
第四步:調(diào)取接口
login.vue
<template> <view class="normal-login-container"> </view> </template> <script setup> import { captchaImageGet } from '@/api/login' // 獲取圖形驗(yàn)證碼 function getCode() { captchaImageGet().then((res) => { console.log(res, 'res') }) } //或者 const getCode = async () => { let res = await captchaImageGet() console.log(res, 'res') } getCode() </script> <style lang="scss"> </style>
總結(jié)
到此這篇關(guān)于uniapp微信小程序axios庫(kù)的封裝及使用詳細(xì)教程的文章就介紹到這了,更多相關(guān)uniapp微信小程序axios庫(kù)封裝內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- UNIAPP實(shí)現(xiàn)微信小程序登錄授權(quán)和手機(jī)號(hào)授權(quán)功能(uniapp做微信小程序)
- 前端uniapp微信小程序跨域問(wèn)題的解決方法
- uniapp實(shí)現(xiàn)微信小程序支付(前端)詳細(xì)代碼
- uniapp微信小程序支付前端生成簽名并調(diào)起微信支付全部代碼
- uniapp微信小程序使用webview嵌套u(yù)niappH5并實(shí)現(xiàn)通信詳細(xì)步驟
- uniapp開(kāi)發(fā)微信小程序主包太大和vendor.js過(guò)大無(wú)法打包問(wèn)題解決
- uniapp微信小程序授權(quán)登錄并獲取手機(jī)號(hào)的方法
- uniapp微信小程序訂閱消息發(fā)送服務(wù)通知超詳細(xì)教程
- uniapp微信小程序多環(huán)境配置以及使用教程
- uniapp 微信小程序之金額展示套餐
相關(guān)文章
element-ui 表格sortable排序手動(dòng)js清除方式
這篇文章主要介紹了element-ui 表格sortable排序手動(dòng)js清除方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-07-07一次用vue3簡(jiǎn)單封裝table組件的實(shí)戰(zhàn)過(guò)程
之所以封裝全局組件是為了省事,所有的目的,全都是為了偷懶,下面這篇文章主要給大家介紹了關(guān)于用vue3簡(jiǎn)單封裝table組件的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),需要的朋友可以參考下2022-12-12vue中使用 pako.js 解密 gzip加密字符串的方法
這篇文章主要介紹了vue項(xiàng)目中 使用 pako.js 解密 gzip加密字符串 的方法,本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2019-06-06關(guān)于Vue實(shí)例創(chuàng)建的整體流程
這篇文章主要介紹了關(guān)于Vue實(shí)例創(chuàng)建的整體流程,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-06-06vue調(diào)試工具vue-devtools的安裝全過(guò)程
這篇文章主要介紹了vue調(diào)試工具vue-devtools的安裝全過(guò)程,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-06-06Vue動(dòng)態(tài)組件和keep-alive組件實(shí)例詳解
動(dòng)態(tài)組件指的是動(dòng)態(tài)切換組件的顯示與隱藏,下面這篇文章主要給大家介紹了關(guān)于Vue動(dòng)態(tài)組件和keep-alive組件的相關(guān)資料,文中通過(guò)實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下2022-05-05對(duì)vue里函數(shù)的調(diào)用順序介紹
下面小編就為大家分享一篇對(duì)vue里函數(shù)的調(diào)用順序介紹,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-03-03