import axios from ‘axios‘ import store from ‘../vuex/store‘ import router from ‘../router/index‘ import { stringify } from ‘qs‘ //qs模块 // axios 配置 axios.defaults.timeout = 5000; axios.defaults.baseURL = ‘‘;//‘http://hzzly.net:4000‘; // http request 拦截器 axios.interceptors.request.use( config => { if (store.state.token) { config.headers.Authorization = `token ${store.state.token}`; } return config; }, err => { return Promise.reject(err); }); // http response 拦截器 axios.interceptors.response.use( response => { return response; }, error => { if (error.response) { switch (error.response.status) { case 401: // 401 清除token信息并跳转到登录页面 //store.commit(types.LOGOUT); router.replace({ path: ‘login‘, query: {redirect: router.currentRoute.fullPath} }); break; case 403: break; case 504: break; case 500: //store.dispatch(types.AJAX_ERROR,500); break; case 404: //store.dispatch(types.AJAX_ERROR,404); break; } } console.log(JSON.stringify(error));//console : Error: Request failed with status code 402 return Promise.reject(error.response.data) }); /*{ type:type, params:params, }*/ // 封装请求 export function fetch (url, options) { var opt = options || {} return new Promise((resolve, reject) => { axios({ method: opt.type || ‘post‘, url: url, params: opt.params || {}, // 判断是否有自定义头部,以对参数进行序列化。不定义头部,默认对参数序列化为查询字符串。 data: (opt.headers ? opt.data : stringify(opt.data)) || {}, responseType: opt.dataType || ‘json‘, // 设置默认请求头 headers: opt.headers || {‘Content-Type‘: ‘application/x-www-form-urlencoded; charset=UTF-8‘} }).then(response => { if (response.data.code === 0) { resolve(response.data) } else if (response.data.code === ‘000‘) { resolve(response.data) } else { reject(response.data) //store.commit(‘SET_LOADING‘, false) } }).catch(error => { console.log(error) reject(error) //store.commit(‘SET_LOADING‘, false) }) }) } export default axios;
使用axios封装的功能
import { fetch } from ‘../../util/api‘ //用户登录 export const userLogin= (data)=> fetch(‘/api/users/api/userLogin‘,{ data, ‘type‘:‘post‘ });
时间: 2024-10-11 05:46:43