最近一个项目要用到token,每次请求都要放到header里面, 看了几篇博文,对axios有了简单的理解, 以下是初始的axios的封装,可根据个人情况而改变

import axios from 'axios'
import Vue from 'vue'
import store from '../store'

//封装axios
const service = axios.create({
  //可以在这里写baseurl
  timeout: 5000,
  withCredentials: true
});

//请求拦截器
service.interceptors.request.use(
  config => {
    config.baseURL = store.getters.apiUrl;
    //为请求设置token
    setTokenToHeader(config);
    return config
  },
  error => {
    return Promise.reject(error)
  }
);

//响应拦截器
service.interceptors.response.use(
  response =>{
    return response;
  },
  error => {

  }
);

function setTokenToHeader(config) {
  // set token
  const token = store.getters.token;
  Vue.$log.debug('Got token from store', token);
  if (token && token.access_token) {
    config.headers['Authorization'] = token.access_token
  }
}

async function reRequest(error) {
  const config = error.response.config;
  setTokenToHeader(config);
  const res = await axios.request(config);
  return res;
}


export default service