uniapp微信小程序axios庫的封裝及使用詳細(xì)教程
方式一
第一步:安裝axios及適配器
安裝依賴
需要注意使用uniapp-vue3版本時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這個依賴主要是適配小程序網(wǎng)絡(luò)請求的適配器,為了解決uniapp 適配axios請求,避免報adapter is not a function錯誤
第二步: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)前處于哪個開發(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ù)可以直接展開
headers: {},
});
}
post(url, data = {}, outHeaders = {}) {
// 請求體中 {}
return this.request({
method: "post",
url,
data, // post要求必須傳入data屬性
headers: {},
});
}
// 設(shè)置攔截器
setInterceptors(instance) {
// 請求攔截器
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("請求獲取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報錯", 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以上版本無法請求問題
//根據(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)前處于哪個開發(fā)環(huán)境
console.log("baseURL:", baseURL, "++++++++++++++++++++++++");
//解決uniapp 適配axios請求,避免報adapter is not a function錯誤
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文件下直接子級login.js文件內(nèi)容
import axios from '@/utils/axios' import login from './config/login' // 獲取驗證碼 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'
// 獲取圖形驗證碼
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庫的封裝及使用詳細(xì)教程的文章就介紹到這了,更多相關(guān)uniapp微信小程序axios庫封裝內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- UNIAPP實現(xiàn)微信小程序登錄授權(quán)和手機(jī)號授權(quán)功能(uniapp做微信小程序)
- 前端uniapp微信小程序跨域問題的解決方法
- uniapp實現(xiàn)微信小程序支付(前端)詳細(xì)代碼
- uniapp微信小程序支付前端生成簽名并調(diào)起微信支付全部代碼
- uniapp微信小程序使用webview嵌套u(yù)niappH5并實現(xiàn)通信詳細(xì)步驟
- uniapp開發(fā)微信小程序主包太大和vendor.js過大無法打包問題解決
- uniapp微信小程序授權(quán)登錄并獲取手機(jī)號的方法
- uniapp微信小程序訂閱消息發(fā)送服務(wù)通知超詳細(xì)教程
- uniapp微信小程序多環(huán)境配置以及使用教程
- uniapp 微信小程序之金額展示套餐
相關(guān)文章
element-ui 表格sortable排序手動js清除方式
這篇文章主要介紹了element-ui 表格sortable排序手動js清除方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-07-07
vue中使用 pako.js 解密 gzip加密字符串的方法
這篇文章主要介紹了vue項目中 使用 pako.js 解密 gzip加密字符串 的方法,本文通過實例代碼給大家介紹的非常詳細(xì),具有一定的參考借鑒價值,需要的朋友可以參考下2019-06-06
vue調(diào)試工具vue-devtools的安裝全過程
這篇文章主要介紹了vue調(diào)試工具vue-devtools的安裝全過程,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-06-06

