欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

uniapp微信小程序axios庫(kù)的封裝及使用詳細(xì)教程

 更新時(shí)間:2023年08月05日 09:53:28   作者:我總是詞不達(dá)意  
這篇文章主要給大家介紹了關(guān)于uniapp微信小程序axios庫(kù)的封裝及使用的相關(guān)資料,Axios是一個(gè)基于promise網(wǎng)絡(luò)請(qǐng)求庫(kù),作用于node.js和瀏覽器中axios-miniprogram-adapteraxios的小程序適配器,需要的朋友可以參考下

方式一

第一步:安裝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)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • element-ui 表格sortable排序手動(dòng)js清除方式

    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ò)程

    一次用vue3簡(jiǎn)單封裝table組件的實(shí)戰(zhàn)過(guò)程

    之所以封裝全局組件是為了省事,所有的目的,全都是為了偷懶,下面這篇文章主要給大家介紹了關(guān)于用vue3簡(jiǎn)單封裝table組件的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),需要的朋友可以參考下
    2022-12-12
  • vue中使用 pako.js 解密 gzip加密字符串的方法

    vue中使用 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)建的整體流程

    這篇文章主要介紹了關(guān)于Vue實(shí)例創(chuàng)建的整體流程,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2024-06-06
  • vue調(diào)試工具vue-devtools的安裝全過(guò)程

    vue調(diào)試工具vue-devtools的安裝全過(guò)程

    這篇文章主要介紹了vue調(diào)試工具vue-devtools的安裝全過(guò)程,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2023-06-06
  • 在Vue2中注冊(cè)全局組件的兩種方法詳解

    在Vue2中注冊(cè)全局組件的兩種方法詳解

    這篇文章主要介紹了在Vue2中注冊(cè)全局組件的兩種方法,非常的細(xì)致,需要的朋友可以參考下
    2022-07-07
  • Vue動(dòng)態(tài)組件和keep-alive組件實(shí)例詳解

    Vue動(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)用順序介紹

    下面小編就為大家分享一篇對(duì)vue里函數(shù)的調(diào)用順序介紹,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2018-03-03
  • vue axios 簡(jiǎn)單封裝以及思考

    vue axios 簡(jiǎn)單封裝以及思考

    axios 是一個(gè)基于Promise 用于瀏覽器和 nodejs 的 HTTP 客戶(hù)端。這篇文章主要介紹了vue axios 簡(jiǎn)單封裝以及思考 ,需要的朋友可以參考下
    2018-10-10
  • 詳解Vuex中g(shù)etters的使用教程

    詳解Vuex中g(shù)etters的使用教程

    在Store倉(cāng)庫(kù)里,state就是用來(lái)存放數(shù)據(jù)。如果很多組件都使用這個(gè)過(guò)濾后的數(shù)據(jù),我們是否可以把這個(gè)數(shù)據(jù)抽提出來(lái)共享?這就是getters存在的意義。我們可以認(rèn)為,getters是store的計(jì)算屬性。本文將具體介紹一下getters的使用教程,需要的可以參考一下
    2022-01-01

最新評(píng)論