1.封装
/**
* axios方法的扩展,添加了结果处理的封装,用法与axios一致
* 用法
* import { request } from 'net'
*
* request({
* baseURL: '', // http://...
* url: '/test', // http://10.206.228.248:3000/mock/35/test
* method: 'get',
* data: { id: '123' },
* mockData: { name: 'jack' }, // 返回此模拟数据
* callback: res => { }, // 自定义返回操作
* headers: { 'token': 'abc' } //
* }).then(json => {
* // console.log(josn)
* })
*
*
*/
import axios from 'axios'
import { MessageBox, Toast, Indicator} from 'mint-ui'
// import Cookies from 'js-cookie'
import router from '../router'
import store from '../store'
axios.defaults.withCredentials = true; // 允许携带cookie
let reqId = 0
let baseURL = urlSrc // 来自public/url.js
function request(props) {
// 如果使用mock数据,直接返回
if (props.mockData) {
return Promise.resolve({ ...props.mockData })
}
// 开发模式使用代理转发-
if (process.env.NODE_ENV === 'development') {
baseURL = 'http://localhost:8080'
}
// 默认值
const dft = {
baseURL,
timeout: 10000,
method: 'get', //
callback: null,
indicator: true, // 是否显示加载器
}
const config = { ...dft, ...props }
config.headers = {
'Content-Type': 'application/json',
'Access-Control-Allow-Credentials': 'true',
// '_TOKEN_KEY_': Cookies.get('_TOKEN_KEY_'),
...props.headers
}
// console.log(config)
// get时候统一使用data代替params
if (config.method.toUpperCase() === 'GET' && config.data) {
config.params = { ...config.data, ...config.params }
}
// if (typeof config.data !== 'string') { config.data = JSON.stringify(config.data) }
// if (config.mock) { config.baseURL = '' }
if (config.indicator) { Indicator.open() }
const pms = new Promise((resolve, reject) => {
// console.log(`req${++reqId}:`, config)
axios(config)
.then(res => {
const { status, data } = res
// console.log(`res${++reqId}:`, res)
const {
errcode, data: d, errmsg, // jwt
response, obj, errorCode, errorMessage, success, succ, msg, result } = data
// 可能不同的接口返回的字段名称会是其中一个,从中选取不是undefined的那一个
const [json] = [response, obj, result, d].filter(el => el != undefined)
const [su] = [succ, success].filter(el => el != undefined)
const [ms] = [msg, errmsg, errorMessage].filter(el => el != undefined)
// console.log('su:', su)
if (su == 'login') {
// 前往登录
Toast('请登录')
const { path } = router.history.current
if (path != '/checkMobile') {
// const phone = window.phone
// debugger
router.push({ path: '/checkMobile' })
}
return
}
// 如果有传入自定义callback,优先!
if (config.callback) {
config.callback(data)
return
}
if (su == false || su == 'fail') {
MessageBox.alert(`${ms}`, '提示')
return
}
if (su == true || su == 'ok') {
resolve(json)
return
}
reject(res)
})
.catch(error => {
console.log('err..:', error)
const { status, data } = error.response || {}
if (status > 300) {
return Toast(`(${status})网络异常,请稍后再试。`)
}
if (status >= 500) {
return MessageBox.alert(`(${status})服务器错误,请稍后再试。`, '提示' )
}
if (status === 404) {
return MessageBox.alert(`(${status})地址错误。`, '提示')
}
MessageBox.alert(`请求发生错误,请稍后再试。`)
}).finally(() => {
Indicator.close()
})
})
return pms
}
Promise.prototype.finally = function (callback) {
let P = this.constructor;
return this.then(
value => P.resolve(callback()).then(() => value),
reason => P.resolve(callback()).then(() => { throw reason })
)
}
export { request, baseURL }
2.使用
request({
// baseURL: 'http://10.206.228.248:3000/mock/35',
url: '/pub/open/webQuery/queryVehicleList',
method: 'post',
}).then(res => {
const { typeMapLens = [] } = res
this.vehicleTypeList = typeMapLens
let obj = {}
typeMapLens.forEach(el => {
const lens = el.lens || []
lens.forEach(len => {
if (!obj[len]) { obj[len] = true }
});
})
let list = Object.keys(obj).sort((p, n) => p - n)
this.vehicleLengthList = list
}).catch(() => '')