ajax.js 2.5 KB

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