nuxtAxios.js 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. import Vue from "vue";
  2. import qs from "qs";
  3. export default function ({
  4. $axios,
  5. redirect,
  6. req,
  7. store,
  8. app,
  9. ...args
  10. }) {
  11. $axios.onRequest(config => {
  12. const contentType = config.headers["Content-Type"];
  13. const isUpload =
  14. contentType === "multipart/form-data" ||
  15. contentType === "application/json";
  16. if (!isUpload) {
  17. config.headers["Content-Type"] = "application/x-www-form-urlencoded";
  18. }
  19. console.log("nuxtAxios...........req.............req");
  20. config.baseURL = store.state.domainConfig.api;
  21. console.log("Before, making request to ", config.url, config.baseURL);
  22. // stringify post data
  23. if (config.method === "post" && !isUpload) {
  24. const data = config.data;
  25. console.log("stringify req data............");
  26. console.log(JSON.stringify(data));
  27. if (typeof data != "string") {
  28. let urlParams = [];
  29. for (const key in data) {
  30. if (data.hasOwnProperty(key)) {
  31. const element = encodeURIComponent(data[key]);
  32. urlParams.push(`${key}=${element}`);
  33. }
  34. }
  35. config.data = urlParams.join("&");
  36. }
  37. }
  38. console.log("After, making request to ", config.url, config.baseURL);
  39. return config;
  40. });
  41. $axios.onResponse(res => {
  42. const data = res.data;
  43. let needLogin = false;
  44. if (res.config && res.config.data && typeof res.config.data === "string") {
  45. const queryData = res.config.data;
  46. // 将请求入参重新解析
  47. const arrQuery = queryData.split("&");
  48. // 遍历每个入参,看有没有needLogin参数,并且参数是true, 表示该接口如果服务器端返回未登录,则强制跳到登录页面
  49. for (let i = 0; i < arrQuery.length; i++) {
  50. const arr = arrQuery[i].split("=");
  51. //找到名称needLogin
  52. if ("needLogin" === arr[0] && (arr[1] === "true" || arr[1] === true)) {
  53. needLogin = true;
  54. break;
  55. }
  56. }
  57. }
  58. if (data.status === 1 || data.filename || data.sign) {} else if (needLogin && data.status === -99) {
  59. if (app.$deviceType.app) {
  60. if (process.server) {
  61. redirect("proginn://login?backToPage=true");
  62. } else {
  63. location.href = "proginn://login?backToPage=true";
  64. }
  65. } else {
  66. if (process.server) {
  67. redirect(store.state.domainConfig.siteUrl + "/?loginbox=show");
  68. } else {
  69. location.href = store.state.domainConfig.siteUrl + "/?loginbox=show&next=" + encodeURIComponent(location.href);
  70. }
  71. }
  72. console.log(req && req.url);
  73. } else {
  74. console.log(JSON.stringify(data));
  75. Vue.prototype.$message.closeAll();
  76. Vue.prototype.$message.error(data.info || data.error || "");
  77. }
  78. return res;
  79. });
  80. $axios.onError(error => {
  81. console.log("err", error);
  82. });
  83. }