1,src文件夹下新建utils/axios.ts
基本配置可以看axios官网
import axios from 'axios';
declare var configURl: any;
// 创建 axios 实例
const http = axios.create({
baseURL: configURl[import.meta.env.MODE].url, // API 的 base_url
timeout: 10000, // 请求超时时间
});
// 添加请求拦截器
http.interceptors.request.use(
config => {
// 在发送请求之前做些什么,比如设置 token 等
// config.headers['Authorization'] = `Bearer ${token}`;
return config;
},
error => {
// 对请求错误做些什么
return Promise.reject(error);
}
);
// 添加响应拦截器
http.interceptors.response.use(
response => {
// 对响应数据做点什么
return response.data;
},
error => {
// 对响应错误做点什么
return Promise.reject(error);
}
);
export default http;
备注:
1-1:axios的baseURL:
vite.config.ts
import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";
import path from "path";
// https://vite.dev/config/
export default defineConfig({
plugins: [vue()],
resolve: {
alias: {
"@": path.resolve(__dirname, "./src"),
},
},
server:{
proxy:{
'/a':{
target: 'http://1.1.1.78:8088', // 后端服务器地址
changeOrigin: true
}
}
}
});
1-2:public下新建文件config.js
const configURl = {
development: { url: '/a' },
production: {}
}
1-3:在index.html中引入
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title></title>
</head>
<body>
<div id="app"></div>
<script type="text/javascript" src="/config.js"></script>
<script type="module" src="/src/main.ts"></script>
</body>
</html>
2,main.ts
import Axios from "./utils/axios.ts";
const app = createApp(App);
app.provide('axios', Axios)
app
.use(router)
.use(ElementPlus, {
locale: zhCn,
})
.mount("#app");
3,页面中使用
import { ref, reactive, onMounted,inject } from 'vue'
import { AxiosInstance } from 'axios';
// 加个非空断言
const $http = inject<AxiosInstance>('axios')!
const getData = () => {
$http.get('/111/222').then(res => {
if (res.code == 200) {
}
})
}