Vue封装axios请求
vue+vite项目目录
axios.js下封装拦截器
import axios from "axios";
// 创建axios的一个实例
let instance = axios.create({
baseURL: "http://www.xxx.com:8080",
timeout: 20000,
});
// 请求拦截器
instance.interceptors.request.use(
function (config) {
return config;
},
function (error) {
// 错误请求做些什么
return Promise.reject(error);
}
);
// 二、响应拦截器 忽略
instance.interceptors.response.use(
function (response) {
return response.data;
},
function (error) {
// 对响应错误做点什么
return Promise.reject(error);
}
);
export default function (method, url, data = null) {
method = method.toLowerCase();
if (method === "post") {
return instance.post(url, data);
} else if (method === "get") {
return instance.get(url, { params: data });
} else if (method === "delete") {
return instance.delete(url, { params: data });
} else if (method === "put") {
return instance.put(url, data);
} else {
console.error("未知的method" + method);
return false;
}
}
music.js封装请求
import music from "./axios";
// 定义接口
// 获取歌手数据
export const getSingList = (params) =>
music("get", "/www/artist/artistInfo", params);
// 获取歌单数据
export const getSongList = (params) =>
music("get", "/www/artist/artistMusic", params);
引用请求
//导入接口
import { getSingList, getSongList } from "@/api/music.js"; //
const getData = () => {
getSingList(query)
.then((res) => {
console.log("请求成功结果", res);
})
.catch((err) => {
console.log("请求失败", err);
});
};