http.js
2.42 KB
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
/*
* @Author: limin
* @Date: 2018-06-25 10:28:18
* @Last Modified by: huyue
* @Last Modified time: 2021-07-16 18:02:05
*/
import { createSign } from './util'
import axios from 'axios'
import qs from 'qs'
function Http(options = {}) {
this.service = axios.create({
withCredentials: true,
method: 'POST'
})
const { response = {}, request = {}, headers, alert, sign, signWay = 'sha1', secret } = options
this.customer = {
response,
alert,
sign,
secret,
signWay
}
const { baseURL, timeout = 3000, withCredentials = true, responseType = 'json' } = request
Object.assign(this.service.defaults, { headers: Object.assign({}, headers, { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' }) }, { baseURL, timeout, withCredentials, responseType })
return this.create()
}
Http.prototype.create = function () {
this.service.interceptors.request.use(
config => {
let { data = {}, sign = true, noSignAttr = [] } = config
if (sign) {
let _configSign = this.customer.sign || {}
data = createSign(Object.assign({}, _configSign, data), this.customer.secret, noSignAttr, this.customer.signWay)
}
const method = config.method.toLocaleLowerCase()
if (method == 'get') {
config.params = data
} else if (method == 'post') {
config.data = qs.stringify(data)
}
return config
},
error => Promise.reject(error)
)
this.service.interceptors.response.use(
({ data: res, config: { returnAll } }) => {
const {
response: { code_key = 'code', errId = 'errId', code_success_value = '0', data_key = 'data' },
alert
} = this.customer
if (returnAll || !alert) {
return res
}
let code = res[code_key]
// let errId = res[errId]
// 特殊的code处理,可以增加
switch (code + '') {
case code_success_value + '':
// 请求成功,不弹提示框,成功code可以更改
break
default:
if (alert) {
alert(res.message || res.msg || '出错了,请联系管理员')
}
break
}
return res[data_key]
},
error => {
const { alert } = this.customer
alert && alert(error.message || '出错了,请联系管理员')
// 返回接口返回的错误信息
return Promise.reject(error)
}
)
this.service.axios = axios
return this.service
}
export default Http