request.js 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. (function (win) {
  2. axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'
  3. // 创建axios实例
  4. const service = axios.create({
  5. // axios中请求配置有baseURL选项,表示请求URL公共部分
  6. baseURL: '/',
  7. // 超时
  8. timeout: 10000
  9. })
  10. // request拦截器
  11. service.interceptors.request.use(config => {
  12. // 是否需要设置 token
  13. // const isToken = (config.headers || {}).isToken === false
  14. // if (getToken() && !isToken) {
  15. // config.headers['Authorization'] = 'Bearer ' + getToken() // 让每个请求携带自定义token 请根据实际情况自行修改
  16. // }
  17. // get请求映射params参数
  18. if (config.method === 'get' && config.params) {
  19. let url = config.url + '?';
  20. for (const propName of Object.keys(config.params)) {
  21. const value = config.params[propName];
  22. var part = encodeURIComponent(propName) + "=";
  23. if (value !== null && typeof(value) !== "undefined") {
  24. if (typeof value === 'object') {
  25. for (const key of Object.keys(value)) {
  26. let params = propName + '[' + key + ']';
  27. var subPart = encodeURIComponent(params) + "=";
  28. url += subPart + encodeURIComponent(value[key]) + "&";
  29. }
  30. } else {
  31. url += part + encodeURIComponent(value) + "&";
  32. }
  33. }
  34. }
  35. url = url.slice(0, -1);
  36. config.params = {};
  37. config.url = url;
  38. }
  39. return config
  40. }, error => {
  41. Promise.reject(error)
  42. })
  43. // 响应拦截器
  44. service.interceptors.response.use(res => {
  45. console.log('---响应拦截器---',res)
  46. if (res.data.code === 0 && res.data.msg === '未登录') {// 返回登录页面
  47. window.top.location.href = '/front/page/login.html'
  48. } else {
  49. return res.data
  50. }
  51. },
  52. error => {
  53. let { message } = error;
  54. if (message == "Network Error") {
  55. message = "后端接口连接异常";
  56. }
  57. else if (message.includes("timeout")) {
  58. message = "系统接口请求超时";
  59. }
  60. else if (message.includes("Request failed with status code")) {
  61. message = "系统接口" + message.substr(message.length - 3) + "异常";
  62. }
  63. window.vant.Notify({
  64. message: message,
  65. type: 'warning',
  66. duration: 5 * 1000
  67. })
  68. //window.top.location.href = '/front/page/no-wify.html'
  69. return Promise.reject(error)
  70. }
  71. )
  72.  win.$axios = service
  73. })(window);