一、先创建三个文件:
- api.js 存放接口列表的
- http.js 封装axios的
- config.js axios的一些配置项
二、config.js
一些基础的配置,如果有其他需求可以自己添加
// import { getSession } from '@/utils';
const config = {
baseURL: 'http://192.168.110.250:3000',
timeout: 15000,
headers: {
'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'
},
// 自定义全局请求头
// headerHandlers: [
// () => new Promise((resolve) => {
// const userInfo = getSession('userInfo');
// resolve({'session': userInfo ? userInfo.session : ''});
// })
// ],
}
export default config;
三、api.js
存放接口的文件,如果接口有很多,可以分模块新建几个js再往里面引入
const apiArr = [
// {
// name: "test", // 接口调用方法名
// path: '/api/test', // 后端路径
// method: "POST", // 默认POST
// headers: {"token": 123}, // 自定义单个接口的请求头
// desc: "登录接口", // 接口描述
// }
{
name: "login",
path: '/api/login',
desc: "登录接口",
}
]
export default apiArr;
四、http.js
import axios from 'axios';
import axiosConfig from './config'; // axios请求配置
import apiArr from './api'; // 用户请求集合
import qs from 'qs';
import { Message } from 'element-ui';
// 创建axios实例
const service = axios.create({
baseURL: axiosConfig.baseURL,
timeout: axiosConfig.timeout,
headers: axiosConfig.headers
});
// 添加请求拦截器
service.interceptors.request.use(function (config) {
// promise动态添加请求头,加完之后再return出config继续请求
const headerHandlers = (axiosConfig.headerHandlers || []).map(handler => {
return handler(config).then((mixHeaders) => Object.assign(config.headers || {}, mixHeaders))
});
return Promise.all(headerHandlers).then(() => config);
}, function (error) {
// 对请求错误做些什么
return Promise.reject(error);
});
// 添加响应拦截器
service.interceptors.response.use(function (response) {
// 对响应数据做点什么
return response.data;
}, function (error) {
// 对响应错误做点什么
Message.error(error.message)
return Promise.reject(error);
});
// 创建请求
const USE_DATA_METHODS = ['POST', 'PUT', 'PATCH', 'DELETE'];
const createRequest = () => {
const hostApi = {};
apiArr.forEach(api => {
hostApi[api.name] = (params) => {
const method = api.method || "POST";
const requestParams = USE_DATA_METHODS.includes(method) ? { data: qs.stringify(params) } : { params: params };
return service({
url: api.path,
method,
headers: {
...api.headers
},
...requestParams,
})
}
});
return hostApi;
}
const apis = createRequest();
export default apis;
五、调用
封装完成后,在main.js里把接口挂到Vue上面
import apis from './request/http';
Vue.prototype.apis = apis;
然后页面里调用