Created
July 3, 2018 12:53
-
-
Save itboos/f1062926528704c999a923bc3121fb63 to your computer and use it in GitHub Desktop.
axios封装请求
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* eslint--disable */ | |
import config from './config'; | |
let url = ''; | |
// 响应拦截器即异常处理 | |
axios.interceptors.response.use(response => { | |
console.log('响应拦截器:', response); | |
return response; | |
}, error => { | |
if (error && error.response) { | |
console.log('error:', error.response); | |
switch (error.response.status) { | |
case 400: | |
error.message = '错误请求'; | |
break; | |
case 404: | |
error.message = '404 Not Found'; | |
this.tip('这是tips.....'); | |
default: | |
} | |
} | |
}); | |
// Add a request interceptor, 请求拦截器 | |
axios.interceptors.request.use(function (config) { | |
console.log('config:', config); | |
// Do something before request is sent 比如: 给参数添加token | |
config.params.token = 'test-token'; | |
return config; | |
}, function (error) { | |
// Do something with request error | |
return Promise.reject(error); | |
}); | |
// axios.defaults.baseURL = '/api'; | |
// 设置默认请求头 | |
// axios.defaults.headers = { | |
// 'X-Requested-With': 'XMLHttpRequest' | |
// } | |
axios.defaults.timeout = 5000; | |
export default { | |
get(path, param) { | |
if (param.host) { | |
url = `${param.host}/${path}`; | |
} else if (param.ohost) { | |
url = `${config.ohost[param.ohost]}/${path}`; | |
} else { | |
url = `${config.host}/${path}`; | |
} | |
axios({ | |
method: 'get', | |
url, | |
headers: param.headers || { 'content-type': 'application/json' }, // { 'content-type': 'application/x-www-form-urlencoded' }, 'text/plain', | |
params: param.data, | |
}).then(res => { | |
param.callback(res.data); | |
}) | |
.catch((error) => { | |
console.log(error); | |
}); | |
}, | |
post(path, param) { | |
if (param.host) { | |
url = `${param.host}/${path}`; | |
} else if (param.ohost) { | |
url = `${config.ohost[param.ohost]}/${path}`; | |
} else { | |
url = `${config.host}/${path}`; | |
} | |
axios({ | |
method: 'post', | |
url, | |
headers: param.headers || { 'content-type': 'application/x-www-form-urlencoded' }, | |
params: param.data, | |
}).then(res => { | |
// 这里可以做全局登录失败的判断 | |
param.callback(res.data); | |
}) | |
.catch((error) => { | |
console.log(error); | |
}); | |
}, | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment