使用时基本参数和 jQuery ajax 一样
ajax: function (opt) {
let opts = opt || {}
if (!opts.url) {
this.$Toast.error('请填写接口地址')
return false
}
let headers = opts.headers || {
'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
}
if (opts.type === 'post' || opts.type === 'put' || opts.type === 'patch') {
headers[csrfHeader] = csrfContent
}
let options = {
method: opts.type || 'get',
url: opts.url,
headers: headers,
// `baseURL` 将自动加在 `url` 前面,除非 `url` 是绝对的,便于传递相对url
baseURL: '/app',
timeout: opts.time || 10 * 1000,
responseType: opts.dataType || 'json',
transformRequest: opt.transformRequest || [function (data) {
if (opts.type === 'post' || opts.type === 'put' || opts.type === 'patch') {
data = Qs.stringify(data)
}
return data
}]
}
if (opts.type === 'post' || opts.type === 'put' || opts.type === 'patch') {
options.data = opts.data || {}
} else {
options.params = opts.data || {}
}
// ajax 请求拦截器
axios.interceptors.response.use(
response => {return response},
error => {
if (error.response) {
switch (error.response.status) {
case 401:
window.location.href = '/login'
}
}
return Promise.reject(error.response.data)
}
)
axios(options).then(function (res) {
if (res.status === 200) {
if (opts.success) {
opts.success(res.data, res)
}
} else {
if (opts.error) {
opts.error(res)
} else {
this.$Toast.error('服务器出错')
}
}
}).catch(function (error) {
if (opts.error) {
opts.error(error)
} else {
this.$Toast.error('服务器出错')
}
})
}
ajaxError: function (res) {
let errorMsg
if (res.code && res.error.errorMsg) {
errorMsg = res.error.errorMsg
} else if (typeof res === 'string' && res.indexOf('<html>') !== -1 && res.indexOf('登陆') !== -1) {
window.location.href = '/login'
} else {
errorMsg = '服务器出错'
}
this.$Toast.error(errorMsg)
}