ajax.js 2.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. import {host,prefix} from './config'
  2. import { getUrlArgObject } from "@utils/tools";
  3. const $ = require('jquery');
  4. $.support.cors = true;
  5. const axios=require('axios');
  6. const qs=require('querystring');
  7. const isLocal = window.location.hostname.indexOf('localhost')!=-1;
  8. const orgin = window.location.origin;
  9. const qhost = isLocal?host+prefix:prefix;
  10. axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
  11. //axios.defaults.baseURL = host; //默认地址
  12. // axios.defaults.timeout = 60000; //请求超时
  13. const securityCode = getUrlArgObject("code");
  14. const appKeyId = getUrlArgObject("appI");
  15. const appKeySecret = getUrlArgObject("appS");
  16. const productId = getUrlArgObject("productId");
  17. axios.interceptors.request.use(
  18. req => {
  19. req.headers.appKeyId = appKeyId;
  20. req.headers.appKeySecret = appKeySecret;
  21. req.headers.securityCode = securityCode;
  22. req.headers.productId = productId;
  23. return req;
  24. },
  25. error => {
  26. return Promise.reject(error);
  27. }
  28. );
  29. //请求响应拦截,401则调到登录页
  30. axios.interceptors.response.use(
  31. response => {
  32. return response;
  33. },
  34. error => {
  35. if((error+'').indexOf('timeout') != -1) {
  36. //alert('网络请求超时')
  37. }
  38. if (error.response) {
  39. switch (error.response.status) {
  40. case 401:
  41. //alert("服务正在升级,请稍后再试");
  42. break;
  43. case 500:
  44. //alert('后台接口报错');
  45. break;
  46. default:
  47. //alert('其他')
  48. break;
  49. }
  50. }
  51. return Promise.reject(error); // 返回接口返回的错误信息
  52. }
  53. );
  54. const post=(url,data,noPrefix)=>{
  55. if(typeof data!=='string'){
  56. data=qs.stringify(data);
  57. }
  58. return axios({
  59. method:'post',
  60. url:url.indexOf('http:')!=-1?url:((noPrefix&&isLocal)?host+url:((noPrefix&&!isLocal)?orgin+url:qhost+url)),
  61. data
  62. });
  63. };
  64. //json传参
  65. const json=(url,data,noPrefix)=>{ //noPrefix:请求地址不加前缀,如预问诊、页面推送接口
  66. //兼容ie8,axios在ie8下content-type设置不成功且会把headers置为null
  67. return axios({
  68. method:'post',
  69. url:url.indexOf('http:')!=-1?url:((noPrefix&&isLocal)?host+url:((noPrefix&&!isLocal)?orgin+url:qhost+url)),
  70. data
  71. });
  72. };
  73. // 导出
  74. const expJson = (url,data) =>{
  75. return axios({
  76. method:'post',
  77. url:url.indexOf('http:')!=-1?url:qhost+url,
  78. data,
  79. contentType: "application/vnd.ms-excel;charset=UTF-8" ,
  80. responseType: 'blob' //必须添加,否则会乱码
  81. });
  82. }
  83. const get=(url)=>{
  84. return axios.get(qhost+url).then(data=>data.data);
  85. };
  86. module.exports={
  87. post,
  88. get,
  89. json,
  90. expJson
  91. };