当前位置:   article > 正文

uniapp 微信小程序axios库的封装及使用_axios-miniprogram-adapter

axios-miniprogram-adapter

方式一

第一步:安装axios及适配器

安装依赖

需要注意使用uniapp-vue3版本时axios的版本需要0.26.0以下,建议锁版本

  1. npm i axios@0.26.0 axios-miniprogram-adapter
  2. &&
  3. yarn add axios@0.26.0 axios-miniprogram-adapter

 axios-miniprogram-adapter这个依赖主要是适配小程序网络请求的适配器,为了解决uniapp 适配axios请求,避免报adapter is not a function错误

第二步:axios二次封装

在utils文件下新建request.js文件

  1. // axios二次封装
  2. // yarn add axios-adapter-uniapp import axiosAdapterUniapp from 'axios-adapter-uniapp'
  3. import { getToken } from "@/utils/auth";
  4. import axios from "axios";
  5. // 小程序axios适配器
  6. import mpAdapter from "axios-miniprogram-adapter";
  7. axios.defaults.adapter = mpAdapter;
  8. import { toast, showConfirm, tansParams } from "@/utils/common";
  9. //根据环境变量获取api地址
  10. let baseURL = process.env.config[process.env.UNI_SCRIPT].VITE_BASE_API;
  11. // let evnName = process.env.config[process.env.UNI_SCRIPT] 获取当前处于哪个开发环境
  12. console.log("baseURL:", baseURL, "++++++++++++++++++++++++");
  13. class HttpRequest {
  14. constructor() {
  15. this.baseURL = baseURL; // 从环境变量中获取api地址
  16. this.timeout = 300000;
  17. }
  18. mergeOptions(options) {
  19. return {
  20. baseURL,
  21. timeout: 300000,
  22. ...options,
  23. };
  24. }
  25. request(options) {
  26. const instance = axios.create();
  27. this.setInterceptors(instance);
  28. const opts = this.mergeOptions(options);
  29. return instance(opts);
  30. }
  31. get(url, data = {}, outHeaders = {}) {
  32. // console.log(data, "data+++++++++++++");
  33. return this.request({
  34. dataType: "json",
  35. method: "get",
  36. url,
  37. params: { ...data }, // get参数可以直接展开
  38. headers: {},
  39. });
  40. }
  41. post(url, data = {}, outHeaders = {}) {
  42. // 请求体中 {}
  43. return this.request({
  44. method: "post",
  45. url,
  46. data, // post要求必须传入data属性
  47. headers: {},
  48. });
  49. }
  50. // 设置拦截器
  51. setInterceptors(instance) {
  52. // 请求拦截器
  53. instance.interceptors.request.use((config) => {
  54. const noLoading = config.headers["NO-LOADING"];
  55. // 是否需要设置 token
  56. const isToken = config.headers["ISTOKEN"] || false;
  57. if (getToken() && isToken) {
  58. config.header["Authorization"] = `Bearer ${getToken()}`;
  59. }
  60. if (!noLoading) {
  61. uni.showLoading({
  62. title: "加载中...",
  63. });
  64. }
  65. config.headers = {
  66. ...config.headers,
  67. };
  68. //console.log('config',config)
  69. return config;
  70. });
  71. // 响应拦截器
  72. instance.interceptors.response.use(
  73. (res) => {
  74. const noLoading = res.config.headers["NO-LOADING"];
  75. if (!noLoading) {
  76. uni.hideLoading();
  77. }
  78. let { data } = res;
  79. // console.log("请求获取data", data)
  80. if (data) {
  81. if (data.code === 200) {
  82. //console.log('data=============', data)
  83. return Promise.resolve(data);
  84. } else {
  85. showConfirm({
  86. content: data.msg,
  87. showCancel: false,
  88. }).then((res) => {
  89. /* if (res.confirm) {
  90. store.dispatch("LogOut").then((res) => {
  91. uni.reLaunch({ url: "/pages/login" });
  92. });
  93. } */
  94. });
  95. return Promise.resolve(data);
  96. }
  97. }
  98. },
  99. (err) => {
  100. console.log("axios报错", err);
  101. uni.hideLoading();
  102. return Promise.reject(err);
  103. }
  104. );
  105. }
  106. }
  107. export default new HttpRequest();

方式二

在request.js文件中做axios适配,不需要安装axios-miniprogram-adapter适配插件

  1. // axios二次封装
  2. import { getToken } from "@/utils/auth";
  3. import { toast, showConfirm, tansParams } from "@/utils/common";
  4. //映入axios相关
  5. import axios from "axios";
  6. import settle from "axios/lib/core/settle";
  7. import buildURL from "axios/lib/helpers/buildURL";
  8. import buildFullPath from "axios/lib/core/buildFullPath"; //解决axios0.19.0以上版本无法请求问题
  9. //根据环境变量获取api地址
  10. let baseURL = process.env.config[process.env.UNI_SCRIPT].VITE_BASE_API;
  11. // let evnName = process.env.config[process.env.UNI_SCRIPT] 获取当前处于哪个开发环境
  12. console.log("baseURL:", baseURL, "++++++++++++++++++++++++");
  13. //解决uniapp 适配axios请求,避免报adapter is not a function错误
  14. axios.defaults.adapter = function (config) {
  15. return new Promise((resolve, reject) => {
  16. const fullurl = buildFullPath(config.baseURL, config.url);
  17. uni.request({
  18. method: config.method.toUpperCase(),
  19. url: buildURL(fullurl, config.params, config.paramsSerializer),
  20. header: config.headers,
  21. data: config.data,
  22. dataType: config.dataType,
  23. responseType: config.responseType,
  24. sslVerify: config.sslVerify,
  25. complete: function complete(response) {
  26. response = {
  27. data: response.data,
  28. status: response.statusCode,
  29. errMsg: response.errMsg,
  30. header: response.header,
  31. config,
  32. };
  33. settle(resolve, reject, response);
  34. },
  35. });
  36. });
  37. };
  38. class HttpRequest {
  39. constructor() {
  40. this.baseURL = baseURL; // 从环境变量中获取api地址
  41. this.timeout = 300000;
  42. }
  43. // ...上面已贴出封装方式
  44. }
  45. export default new HttpRequest();

第三步: 创建接口配置js文件

在src目录下创建api文件夹,目录结构如下图

 

config文件下login.js文件内容

  1. export default {
  2. captchaImage: "/captchaImage"
  3. }

 api文件下直接子级login.js文件内容

  1. import axios from '@/utils/axios'
  2. import login from './config/login'
  3. // 获取验证码
  4. export const captchaImageGet = () => axios.get(login.captchaImage)

第四步:调取接口

login.vue

  1. <template>
  2. <view class="normal-login-container"> </view>
  3. </template>
  4. <script setup>
  5. import { captchaImageGet } from '@/api/login'
  6. // 获取图形验证码
  7. function getCode() {
  8. captchaImageGet().then((res) => {
  9. console.log(res, 'res')
  10. })
  11. }
  12. //或者
  13. const getCode = async () => {
  14. let res = await captchaImageGet()
  15. console.log(res, 'res')
  16. }
  17. getCode()
  18. </script>
  19. <style lang="scss">
  20. </style>

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/weixin_40725706/article/detail/218980
推荐阅读
相关标签
  

闽ICP备14008679号