ajax.js 2.2 KB

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