axios.js 1.58 KB
import axios from 'axios'
import store from '../store/index.js'

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

// 设置 post、put 默认 Content-Type
service.defaults.headers.post['Content-Type'] = 'application/json'
service.defaults.headers.put['Content-Type'] = 'application/json'

// 添加请求拦截器
service.interceptors.request.use(
  (config) => {
	  if (store.state.users.atoken) {  // 判断是否存在token,如果存在的话,则每个http header都加上token
		  config.headers.authorization = store.state.users.atoken;
	  }
	  if (config.method == 'post') {
	   config.data = {
		 ...config.data,
		 _t: Date.parse(new Date()) / 1000
	   }
	 } else 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)
	  let info = {}

    if (!error.response) {
      info = {
        code: 5000,
        msg: 'Network Error'
      }
    } else {
		let { status, statusText, data } = error.response
      // 此处整理错误信息格式
      info = {
        code: status,
        data: data,
        msg: statusText
      }
    }
	return Promise.reject(error)
  }
)

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