import axios from 'axios';

import { kuky_Authorization } from './storage';
import replaceProxyUrl from './ajax/replace-proxy-url';

const ajax = axios.create({
  withCredentials: true, // 跨域发送 cookie
  timeout: 1000 * 60 * 10, // 请求超时
  headers: {
    'Content-Type': 'application/json'
  }
});

ajax.interceptors.request.use(
  (config) => {
    replaceProxyUrl(config);

    const token = kuky_Authorization.get();
    if (token) {
      config.headers['Authorization'] = `Bearer ${token}`;
    }

    return config;
  },
  (error) => {
    // 请求出错
    return Promise.reject(error);
  }
);

ajax.interceptors.response.use(
  (response) => {
    const res_data = response.data;
    const { code, data, msg } = res_data;

    return res_data;
  },
  (error) => {
    return Promise.reject(error);
  }
);

export default ajax;
