请求拦截封装

src>api>axiosFun.js

import axios from 'axios';
import qs from 'qs'

var root = process.env.API_ROOT //调用环境配置
axios.defaults.baseURL =root;

// 登录请求
const loginreq = (method, url, params) => {
    console.log(url);
    return axios({
        method: method,
        url: url,
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        data:params

    }).then(res => res.data);
};
// 请求
const req = (method, url, params) => {
    console.log(url);
    return axios({
        method: method,
        url: url,
        data:params
//         data: method === 'post' || method === 'put' || method === 'delete' ?data: null,
//         params: method === 'get' ? params : null,
    }).then(res => res.data);

};

axios.interceptors.request.use(function (config) { 
    console.log(config);
    console.log(config.url)  
    if(config.url=='xxx'){
        config.data=config.data;
         config.headers = {
                    'Content-Type':'multipart/form-data;',
                    'token': localStorage.getItem('logintoken'),
                  }   
            console.log(999)
    }else if(config.url=='xx'){
        config.data=config.data;
         config.headers = {
                    'Content-Type':'multipart/form-data;',
                    'token': localStorage.getItem('logintoken')
                  }   
            console.log(999)
    }else{
        config.data=qs.stringify(config.data);
         config.headers = {
                    'Content-Type':'application/x-www-form-urlencoded',
                    'token': localStorage.getItem('logintoken')
                  }   
    }
   
    return config;
        }, function (error) {          
            return Promise.reject(error);
        });


response 拦截器
axios.interceptors.response.use(
    response => {

      const res = response.data;
      if(response.status == 200){
        if(res.code == 0){
          return res
        }else {
              Notify({
                message: res.message,
                duration: 3000,
                background:'#1989fa'
              });
          return Promise.reject('error')
        }
      }
    },
    error => {

      if(error.code =='ECONNABBORTED'){
        Notify({
          message: "连接超时",
          duration: 3000,
        });
      }else if(error.code==530 ||error.code==531){
        Notify({
          message: 'token过期,请重新登陆',
          duration: 3000,
        });
      }else {
        Notify({
          message: error.message,
          duration: 3000,
        });
      }
    }
  );



export {
    loginreq,
    req
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值