Blame view

src/https.js 1.42 KB
35b48aa6   liuqimichale   init
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
58
59
60
61
62
63
64
65
  import axios from 'axios'
  
  axios.defaults.timeout = 5000
  axios.defaults.baseURL = ''
  
  // post请求头
  axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8';
  
  // http request 拦截器
  axios.interceptors.request.use(
    config => {
      return config
    },
    error => {
      return Promise.reject(error)
    }
  )
  
  // http response 拦截器
  axios.interceptors.response.use(
    response => {
      // 如果返回的状态码为200,说明接口请求成功,可以正常拿到数据
      // 否则的话抛出错误
      if (response.status === 200) {
        return Promise.resolve(response);
      } else {
        return Promise.reject(response);
      }
    },
    error => {
      return Promise.reject(error)
    }
  )
  
  /**
   * get方法,对应get请求
   * @param {String} url [请求的url地址]
   * @param {Object} params [请求时携带的参数]
   */
  export function get(url, params) {
    return new Promise((resolve, reject) => {
      axios.get(url, {
        params: params
      }).then(res => {
        resolve(res.data)
      }).catch(err => {
        reject(err.data)
      })
    })
  }
  
  /**
   * post方法,对应post请求
   * @param {String} url [请求的url地址]
   * @param {Object} params [请求时携带的参数]
   */
  export function post(url, params) {
    return new Promise((resolve, reject) => {
      axios.post(url, QS.stringify(params)).then(res => {
        resolve(res.data)
      }).catch(err => {
        reject(err.data)
      })
    })
  }