axios.js 1.1 KB
import axios from "axios";
import store from "../store/index.js";
import router from "../router/index";

// 创建 axios 实例
let service = axios.create({
  // headers: {'Content-Type': 'application/json'},
  timeout: 60000
});

// 添加请求拦截器
service.interceptors.request.use(
  config => {
    let token = localStorage.getItem("atoken");
    if (token) {
      // 判断是否存在token,如果存在的话,则每个http header都加上token
      config.headers.authorization = token;
    } else {
      router.push("/login");
    }
    if (config.method == "get") {
      config.params = {
        _t: Date.parse(new Date()) / 1000,
        ...config.params
      };
    }
    return config;
  },
  error => {
    // 请求错误处理
    return Promise.reject(error);
  }
);

// 添加响应拦截器
service.interceptors.response.use(
  response => {
    let { data } = response;
    return data;
  },
  error => {
    console.log(error);
    return Promise.reject(error);
  }
);

/**
 * 创建统一封装过的 axios 实例
 * @return {AxiosInstance}
 */
export default function() {
  return service;
}