vue3中axios配置相关
安装axios依赖
yarn add axios 或 npm install axios --save
src目录下创建相关文件夹

相关文件内容
【config/request.js】
import axios from "axios";
// import store from "@/store";
// 创建并配置一个新的axios
const service = axios.create({
baseURL: process.env.VUE_APP_BASE_API, // 这里指所有接口请求的“请求地址前缀”,完整请求地址 = 请求地址前缀 + 接口后缀,即 url = baseURL + request url
timeout: 60000, // 请求超时时间 毫秒
withCredentials: true, // 异步请求时是否携带cookie
headers: { // 设置后端需要的传参类型
"Content-Type": "application/json",
// token: "your token",
// "X-Requested-With": "XMLHttpRequest",
},
});
// 添加请求拦截器
service.interceptors.request.use(
(config) => {
// 在发送请求之前做些什么。。。
// 比如配置请求token(如果需要的话)
// const tokenInfo = store.state.account.tokenInfo;
// if (tokenInfo && tokenInfo.tokenName) {
// config.headers[tokenInfo.tokenName] = tokenInfo.tokenValue; //配置请求token
// }
return config;
},
(error) => {
// 对请求错误做些什么
return Promise.reject(error);
}
);
// 添加响应拦截器
service.interceptors.response.use(
(response) => {
const res = response.data;
if (res.code == 401) {
//登录拦截:接口需要登录,但用户未登录
// store.commit("account/setUserInfo", ""); //移除用户信息
// if(confirm("登录失效,是否重新登录")){
// console.log("确定")
// }else{
// console.log("取消")
// }
return Promise.reject(new Error(res.msg || "Error"));
} else {
//其他情况则返回结果,对应状态code需在具体请求函数里判断
return res;
}
},
(error) => {
// alert(error.msg || "服务器开小差了呢,请稍后再试~");
return Promise.reject(error);
}
);
export default service;
【apis/demo.js】
如何请求?看这里:https://www.cnblogs.com/huihuihero/p/12713207.html
// demo页
import request from "@/services/config/request";
/**
* 这是一个get请求,使用params传参
* @param {*} params
*/
async function getVideoInfo(params) {
return request({
url: `/video/getvideo`,
method: "get",
params: params,
});
}
/**
* 这是一个get请求,直接在接口里带参
*/
async function getVideoInfoById(id) {
return request({
url: `/video/getvideo/${id}`,
method: "get",
});
}
/**
* 这是一个post请求,使用data传参
* @param {*} params
*/
async function addVideoInfo(params) {
return request({
url: `/video/addvideo`,
method: "post",
data: params,
});
}
export default {
getVideoInfo,
getVideoInfoById,
addVideoInfo,
};
【apis/index.js】
/* ----- 所有接口汇总 ----- */
import userApi from "./user.js"; //用户相关接口
import commonApi from "./common.js"; //通用相关接口
export {
userApi,
commonApi
};
如何使用
import { commonApi } from "@/services/apis";
setup() {
function getVideoInfo() {
let params = {
videoid: 666,
};
commonApi.getVideoInfo(params).then((res) => {});
}
getVideoInfo();
},
如何全局挂载axios
【方案一 推荐】
添加,在main.js中
const app=createApp(App)
import axios from "axios";
app.config.globalProperties.$axios = axios;
引入
import { getCurrentInstance } from "vue";
const { $axios } = getCurrentInstance().appContext.config.globalProperties;
【方案二】
添加,在main.js中
const app=createApp(App)
import axios from "axios";
app.provide('$axios', axios)
引入
import { inject } from 'vue'
const $axios = inject('$axios')

浙公网安备 33010602011771号