ajax.js 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  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 qhost = isLocal?host+prefix:prefix;
  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. axios.interceptors.request.use(
  17. req => {
  18. req.headers.appKeyId = appKeyId;
  19. req.headers.appKeySecret = appKeySecret;
  20. req.headers.securityCode = securityCode;
  21. return req;
  22. },
  23. error => {
  24. return Promise.reject(error);
  25. }
  26. );
  27. //请求响应拦截,401则调到登录页
  28. axios.interceptors.response.use(
  29. response => {
  30. return response;
  31. },
  32. error => {
  33. if((error+'').indexOf('timeout') != -1) {
  34. //alert('网络请求超时')
  35. }
  36. if (error.response) {
  37. switch (error.response.status) {
  38. case 401:
  39. //alert("服务正在升级,请稍后再试");
  40. break;
  41. case 500:
  42. //alert('后台接口报错');
  43. break;
  44. default:
  45. //alert('其他')
  46. break;
  47. }
  48. }
  49. return Promise.reject(error); // 返回接口返回的错误信息
  50. }
  51. );
  52. const post=(url,data)=>{
  53. if(typeof data!=='string'){
  54. data=qs.stringify(data);
  55. }
  56. return axios({
  57. method:'post',
  58. url:qhost+url,
  59. data
  60. });
  61. };
  62. //json传参
  63. const json=(url,data)=>{
  64. //兼容ie8,axios在ie8下content-type设置不成功且会把headers置为null
  65. return axios({
  66. method:'post',
  67. url:url.indexOf('http:')!=-1?url:qhost+url,
  68. data
  69. });/*new Promise((resolve,reject)=>{
  70. $.ajax({
  71. method:'post',
  72. url:qhost+url,
  73. data:JSON.stringify(data),
  74. contentType:"application/json; charset=UTF-8",
  75. success:function(res){
  76. resolve({data:res});
  77. },
  78. error:function(error){
  79. reject(error);
  80. },
  81. });
  82. });*/
  83. };
  84. const get=(url)=>{
  85. return axios.get(qhost+url).then(data=>data.data);
  86. };
  87. module.exports={
  88. post,
  89. get,
  90. json
  91. };