Axios secondary packaging in vue

foreword

When developing a Vue project or a React project, we all need to do a very important job, which is to send a request to the backend to obtain data, so in order to be able to send requests more flexibly and conveniently, we usually do a second round of axios before development Encapsulation, before encapsulation, it is still a simple axios understanding



  1. npm i axios download axios plugin


  1. Create a new utils folder and create a new http.js file

import axios from "axios"; // 引入axios

// 实例化axios并设置网络延迟两秒

const instance = axios.create({
  timeout: 2000,
});

// 设置post请求头
instance.defaults.headers.post["Content-Type"] =
  "application/json;charset=utf-8";

// 请求拦截器
instance.interceptors.request.use(
  // 请求数据接口之前的一些逻辑操作,例如:判断token是否存在、配置请求头
  (config) => {
    //设置请求头
    if (localStorage.getItem("token")) {
      config.headers.common["token"] = localStorage.getItem("token");
    }
    return config;
  },
  (error) => Promise.reject(error)
);

// 响应拦截器
instance.interceptors.response.use(
  (res) => {
    // 响应回来的数据,做一些逻辑操作
    console.log(res);
  },
  // 失败做的一些逻辑
  (error) => Promise.error(error.response)
);

// 导出二次封装的axios
export default instance;

  1. Mount the global object in main.js

import { createApp } from "vue";
import App from "./App.vue";
import http from "@/utils/http";
const app = createApp(App); // 实例化app

app.config.globalProperties.$http = http; // 在全局挂载二次封装的axios

app.mount("#app");

  1. used in the file

<script>
export default {
  methods: {
    addList(){
        this.$http.post("/路径").then(res => {
            console.log(res)  
      })
    }
  },
};
</script>

Guess you like

Origin blog.csdn.net/m0_71349739/article/details/128797419