import Qs from "qs";
import axios from "axios";

const TIMEOUT = 10000;

const instance = axios.create({
  timeout: TIMEOUT, // 请求超时时间
});

instance.interceptors.request.use(
  (config) => {
    if (config.method === "get") {
      config.data = true;
    }
    config.method === "post"
    ? (config.data = Qs.stringify({ ...config.data, _t: Date.now() }))
    : (config.params = { ...config.params, _t: Date.now() });
    config.headers["Content-Type"] = "application/x-www-form-urlencoded";

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

// 响应拦截器
instance.interceptors.response.use(
  // 请求成功
  (res) => {
    const { status } = res || -1000;
    return (status >= 200 && status <= 400) ? res.data : res
  }
);

export default instance;
