安装axios
1.通过vue ui引入
2.手敲
install axios -S
axios文件结构

axios:存放axios实例
/**
* axios请求插件
* @author flytoyou
*/
import axios from 'axios';
import getEnv from "../utils/getEnv";
// 创建axios实例
const instance = axios.create({
baseURL: getEnv().env,//请求的url由工具配置
timeout: 10000,
headers: {
'Content-Type': 'application/json'
},
withCredentials: false
});
/**
* request过滤器
* 此处为发送请求前的过滤操作
*/
instance.interceptors.request.use((config) => {
config.headers['Authorization'] = localStorage.getItem('yyq_token') || '';
return config;
}, (err) => {
// 将错误抛出,供程序处理
return Promise.reject(err);
});
/**
* response过滤器
* 此处为请求返回时的过滤操作
*/
instance.interceptors.response.use((response) => {
return response.data;
}, (err) => {
// 将错误抛出,供程序处理
return Promise.resolve(err);
});
// 返回axios实例
export default instance;
getEnv:用来存放请求用的参数
/**
* 根据环境返回请求参数
*/
export default function getEnv () {
const protocol = window.location.protocol;
const host = window.location.host;
let socketURL = 'ws://xxxx:9999';
let bucket = 'xxxxxx';
let env = 'http://xxxxxx:10002';
if (/^(test-|localhost|192)/.test(host) || !host) {
//将内容配置为对应的参数
}
return {
env,
bucket,
socket: socketURL
};
}
api:用来存放各个api模块
以system.js为例
import axios from '../axios';
export default {
/**
* 查询版本
*
* @returns 后台返回的数据
*/
systemVersion() {
return axios({
method: 'get',
url: '/cfg/systemVersion',
noLoading: true
});
}
}
使用axios
导入api实例
import system from "../api/system";
发送axios请求
system.systemVersion().then((res) => {
console.log(res)
}).catch((err) => {
console.log(err)
});
网友评论