十、vue二次封装axios

下载axios

cnpm install --save axios

 

新建项目

 

 配置axios二次封装文件reques.js

复制代码
//对axios进行二次封装
import axios from "axios";

//1:利用axios对象的方法create,去创建一个axios实例
//2:request就是axios,只不过稍微配置一下
const requests = axios.create({

  //配置对象
  //基础路径,发请求的时候,路径当中会出现api
  baseURL: "http://120.24.235.216:9000",
  //代表请求超时的时间5S,超时停止
  timeout: 5000,
})
//请求拦截器:在发请求之前,请求拦截器可以检测到,可以在请求发出去之前做一些事情
requests.interceptors.request.use((config) => {
  //请求拦截器:在发请求之前,请求拦截器可以检测到,可以在请求发出去之前做一些事情
  return config;
})

//响应拦截器
requests.interceptors.response.use((res) => {
  //成功的回调函数:服务器相应数据回来以后,响应拦截器可以检测到,可以做一些事情
  return res.data; //简化数据返回获取数据的调取

}, (error) => {
  //响应失败的回调函数
  console.log(error)
  return Promise.reject(new Error('faile'));
})

//对外暴露
export default requests
复制代码

配置接口统一管理文件index.js

import requests from "./request"
export function getChannelData () {
  return requests({
    url: '/auth/admin/video/partition/queryAllPartition',

  })
}

 使用接口(单独导入使用)

复制代码
import { getChannelData } from "../api/index";
export default {
  name: "HelloWorld",
  data() {
    return {
      data: "",
    };
  },
  methods: {
    test() {
      getChannelData().then((res) => {
        this.data = res;
        console.log(res);
      });
    },
  },
复制代码

 使用接口(全局导入使用,则this.$API直接调用即可)

 axios的基本授权原生用法

复制代码
      var data = { id: 278 };
      console.log(qs.stringify(data));
      axios({
        method: "post",
        url: "http://192.168.0.101:8080/test/72b88c04309911ec8d3d0242ac130003/v1_0_0/testprovider/get",
        headers: {
          "Content-Type": "application/x-www-form-urlencoded",
          Authorization:
            "Basic " + btoa("testeradmin" + ":" + "testerpassword"), //基本授权
        },
        data: qs.stringify(data),
      }).then((result) => {
        console.log(result);
      });
    },
复制代码

二次封装拦截器用法

 

posted on   QiKS  阅读(199)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

导航

统计

点击右上角即可分享
微信分享提示