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
npm i axios download axios plugin
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;
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");
used in the file
<script>
export default {
methods: {
addList(){
this.$http.post("/路径").then(res => {
console.log(res)
})
}
},
};
</script>