nuxtAxios.js 2.8 KB

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