自己封装Axios

前端整合 Axios,并自定义 Axios 实例,完成请求。
官网:https://www.axios-http.cn/docs/intro
调用后端接口时需要使用Axios

步骤

  1. 安装 Axios
npm install axios
  1. 创建实例

创建 plugins 目录

image-20230326143348796

坐标:plugins/myAxios.ts

import axios from "axios";

const instance = axios.create({
  baseURL: "http://localhost:9090/api",
  timeout: 10000,
  headers: {},
});

export default instance;
  1. 测试请求响应

坐标:pages/IndexPage.vue

<script setup lang="ts">
    import myAxios from "@/plugins/myAxios";
    myAxios.post("/post/get/vo?id=" + "123456").then((res) => {
      	console.log(res);
    });
</script>
  1. 可以通过 res.data 获取数据,但是每个接口都要写一次,比较麻烦。因此添加全局响应拦截器

Axios 拦截器:https://www.axios-http.cn/docs/interceptors

坐标:plugins/myAxios.ts

// 添加响应拦截器
axios.interceptors.response.use(
    function (response) {
        // 2xx 范围内的状态码都会触发该函数。
        // 对响应数据做点什么
        return response;
    }, function (error) {
        // 超出 2xx 范围的状态码都会触发该函数。
        // 对响应错误做点什么
        return Promise.reject(error);
	}
);

完整代码

import axios from "axios";

const instance = axios.create({
  baseURL: "http://localhost:8102/api",
  timeout: 10000,
  headers: {},
});

// 添加响应拦截器
instance.interceptors.response.use(
  function (response) {
    // 2xx 范围内的状态码都会触发该函数。
    // 对响应数据做点什么
    const data = response.data;
    if (data.code === 0) {
      return data.data;
    }
    console.error("request error: " + data);
    return response.data;
  },
  function (error) {
    // 超出 2xx 范围的状态码都会触发该函数。
    // 对响应错误做点什么
    return Promise.reject(error);
  }
);

export default instance;

然后接下来前端向后端发送请求

例子:
编写获取文章接口
坐标:pages/IndexPage.vue

<template>
  {{ JSON.stringify(postList) }}
</template>

<script setup lang="ts">
import myAxios from "@/plugins/myAxios";
    
myAxios.post("/post/list/page/vo", {}).then((res: any) => {
    postList.value = res.records;
});
</script>

后面应该有更精简的写法的!封装的更简洁

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值