一、vue2.0项目中
1.配置
import axios from 'axios';
import { Message } from 'element-ui';
import router from '../../router/index.js';
const service = axios.create({
timeout: 600000,
withCredentials: false,
});
service.interceptors.request.use(
config => {
config.headers['Content-Type'] = 'application/json';
config.headers['aiToken'] = JSON.parse(localStorage.getItem('token'));
config.url = process.env.VUE_APP_WEB_API + config.url;
if (config.params) {
config.params.f_rnd = new Date().getTime();
} else {
config.params = {
f_rnd: new Date().getTime(),
};
}
return config;
},
error => {
return Promise.reject(error);
}
);
service.interceptors.response.use(
response => {
let data = response.data;
if (response.config.isExport) {
return response;
}
if (data.code === 200) {
return data;
} else {
if (data.code === 1015) {
Message({
type: 'error',
offset: 12,
message: '登录/授权已经过期,请重新登录',
duration: 5000,
});
router.push({ path: '/login' });
return;
}
Message({
showClose: true,
message: data.message || data.msg,
duration: 2000,
type: 'error',
});
return Promise.reject(data);
}
},
error => {
console.log('error:' + error);
return Promise.reject(error);
}
);
export default service;
2.使用
import request from '@/assets/js/axios.js';
export function wordClould(params) {
return request({
url: `url`,
method: 'get',
params,
});
}
export function adviserWordClould(data) {
return request({
url: 'url',
method: 'post',
data,
});
}
二、vue2.0+ts项目中如何配置
1.配置
import axios from 'axios';
import { AxiosResponse, InternalAxiosRequestConfig, AxiosError } from 'axios';
import { Message } from 'element-ui';
const request = axios.create({
timeout: 50000,
withCredentials: false,
});
request.interceptors.request.use(
function (config: InternalAxiosRequestConfig<any>) {
if (config.headers) {
config.headers['Authorization'] = 'token';
}
config.url = process.env.VUE_APP_WEB_API + config.url;
return config;
},
function (error: AxiosError) {
return Promise.reject(error);
}
);
interface responseConfig {
status: number;
}
request.interceptors.response.use(
function (response: AxiosResponse<responseConfig>) {
if (response.data.status === 200) {
return response;
}
Message.error('后台接口异常,请联系管理员');
return Promise.reject(response);
},
function (error: AxiosError) {
return Promise.reject(error);
}
);
export default request;
2.使用
export interface paramsType {
[key: string]: any;
}
import request from '../utils/axios';
import { paramsType } from '../utils/types';
export function ApiLogin(data: paramsType) {
return request({
method: 'POST',
url: 'url',
data,
});
}
export function APIGetMenu(params: paramsType) {
return request({
method: 'GET',
url: 'url',
params,
});
}