Blame view

src/api/axios.js 1.56 KB
c1b532ad   梁保满   权限配置,路由基础设置
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
  import axios from "axios"
  import Cookies from "js-cookie"
  import NProgress from "nprogress"
  import { Message } from "element-ui"
  // axios默认配置
  axios.defaults.timeout = 10000 // 超时时间
  axios.defaults.baseURL = process.env.API_HOST
  
  // http request 拦截器
  axios.interceptors.request.use(config => {
    NProgress.start()
    config.headers["Content-Type"] = "application/json;charset=UTF-8"
    if (Cookies.get("access_token")) {
      config.headers.Authorization = "Bearer" + Cookies.get("access_token")
    }
    return config
  },
  error => {
    return Promise.reject(error.response)
  })
  
  // http response 拦截器
  axios.interceptors.response.use(
    response => {
      NProgress.done()
      if (response.data.code === 11000) {
        Cookies.set("access_token", response.data.message, { expires: 1 / 12 })
        return Promise.resolve()
      } else if (response.data.code === 10000) { // 约定报错信息
        Message({
          message: response.data.message,
          type: "warning"
        })
        return Promise.reject(response)
      } else {
        return Promise.resolve(response)
      }
    },
    error => {
      if (error.response.status === 404) {
        Message({
          message: "请求地址出错",
          type: "warning"
        })
      } else if (error.response.status === 401) {
        Message({
          message: error.response.data.message,
          type: "warning"
        })
        Cookies.remove("access_token")
        setTimeout(() => {
          location.reload()
        }, 3000)
      }
      return Promise.reject(error.response) // 返回接口返回的错误信息
    })
  export default axios