import axios from "axios";
import qs from 'qs'
// let jwt=require('express')
axios.defaults.timeout=30000;  //响应时间
axios.defaults.headers.post["Content-Type"]=
         "application/x-www-form-urlencoded";"charset=UTF-8;"
   
    
axios.defaults.baseURL='http://10.3.16.76:2004'  //接口地址

// 请求拦截
axios.interceptors.request.use(
    (config)=>{
        let token = sessionStorage.getItem('assess_token') || ''; //获取token
        // console.log(token);
        if(token !=''){
            config.headers={
                // 'assess_token':token,
                'Authorization':token,
                "Content-type":"application/x-www-from-urlencoded"
            };
            console.log(config.headers);
        }
        // console.log(config);
        // config.data=qs.stringify(config.data)  //序列化post参数
        // console.log(config.data);
        return config;
    },
    (error)=>{
        console.log("错误的传参");
        return Promise.reject(error)
    }
)

// 响应拦截
axios.interceptors.response.use(
     (res)=> {
        // console.log(res);
        if (res.data.status==0) {
            let newToken=res.data.token;//成功后更新token
            sessionStorage.setItem("assess_token",newToken)
        }
    return res;
  },
  (error)=>{
    if(error.res.data.status=="401"){
        this.$router.push('/login')
    }
    return Promise.reject(error);
  });

  function post(url,params){
    return new Promise((resolve,reject)=>{
        axios
            .post(url,params)
            .then(
                (res)=>{
                    resolve(res)
                },
                (err)=>{
                    reject(err)
                }
            )
            .catch((error)=>{
                reject(error)
            });
    });
  }

  function get(url,param){
    return new Promise((resolve,reject)=>{
        axios
            .get(url,{params:param})
            .then((res)=>{
                resolve(res);
                },
                (err)=>{
                    reject(err)
                }
            )
            .catch((error)=>{
                    reject(error)
            });
    })
  }

  export default{
    get,
    post,
  }