美文网首页
react+antd 封axios拦截请求和响应拦截

react+antd 封axios拦截请求和响应拦截

作者: 冷r | 来源:发表于2019-09-23 20:57 被阅读0次

    import axios from 'axios';
    import qs from 'qs';
    import { getCookies } from '@/util/index';

    const request = axios.create({
    // baseURL: process.env.BASE_URL,
    timeout: 5000
    });

    // 拦截请求
    request.interceptors.request.use(config => {
    config.method === 'post' ?
    (config.data = qs.stringify({...config.data })) :
    (config.params = {...config.params });
    config.headers['Content-Type'] = 'application/x-www-form-urlencoded';
    if (config.url !== '/user/login') {
    config.headers['authorization'] = getCookies('token');
    }
    if (!getCookies('token') && config.url !== '/user/login') {
    window.location.href = '/login';
    }
    return config;
    });
    // 添加响应拦截
    request.interceptors.response.use(
    response => {
    // 直接返回response.data
    return response;
    },
    error => {
    const { status, data } = error.response;
    switch (status) {
    case 401:
    alert('登录失败,请重新登录');
    break;
    case 422:
    alert(data.msg);
    break;
    default:
    alert('请稍后重试');
    }
    }
    );
    export default request;

    相关文章

      网友评论

          本文标题:react+antd 封axios拦截请求和响应拦截

          本文链接:https://www.haomeiwen.com/subject/zvfgyctx.html