axios请求封装
小于 1 分钟
axios请求封装
1.utils工具包==>封装axios
//utils==>http.js
//axios的基础封装
import axios from "axios";
const httpInstance = axios.create({
baseURL: 'https://tcsday.com',
timeout: 5000
})
// axios请求拦截器
httpInstance.interceptors.request.use(config => {
return config
}, e => Promise.reject(e))
// axios响应式拦截器
httpInstance.interceptors.response.use(res => res.data, e => {
return Promise.reject(e)
})
//默认导出
export default httpInstance
2.api包定义请求
//按板块区分js文件 home.js
//默认导入
import httpInstance from "@/utils/http"
/**
* @description: 获取新鲜好物
* @param {*}
* @return {*}
*/
export const getNewAPI = () => {
return httpInstance({
url: '/home/new'
})
}
3.组件调用接口,发送数据
//HomeNew.vue
<script setup>
import HomePanel from "./HomePanel.vue";
import { getNewAPI } from "@/apis/home";
import { ref } from "vue";
//定义数组响应式数据
const newList = ref([]);
const getNewList = async () => {
//调用定义的api接口
const res = await getNewAPI();
newList.value = res.result;
};
//调用函数发送请求获取数据
getgoods();
</script>