nuxtAxios.js 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. import Vue from 'vue';
  2. import qs from 'qs';
  3. export default function ({ $axios, redirect, req, ...args }) {
  4. $axios.onRequest(config => {
  5. config.headers['Content-Type'] = 'application/x-www-form-urlencoded';
  6. console.log('Before, making request to ', config.url, config.baseURL)
  7. const referer = config.headers.common && config.headers.common.referer;
  8. const url = config.url;
  9. if (referer && !(/https?/.test(url))) {
  10. // server http
  11. config.url = referer.split('/').slice(0, 3).join('/') + url;
  12. config.baseURL = referer.split('/').slice(0, 3).join('/');
  13. } else {
  14. // client http
  15. config.url = /https?/.test(url) ? `/${url.split('/').slice(3).join('/')}` : url;
  16. config.baseURL = '';
  17. }
  18. // stringify post data
  19. if (config.method === 'post') {
  20. // config.headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8';
  21. const data = config.data;
  22. // const cookie = config.headers.cookie || config.headers.common.cookie || '';
  23. let formData = '';
  24. for(const key in data) {
  25. if(data.hasOwnProperty(key)) {
  26. const element = data[key];
  27. formData += `${key}=${element}&`;
  28. }
  29. }
  30. // formData += cookie.split(';').join('&');
  31. config.data = formData;
  32. // config.data = qs.stringify(config.data);
  33. }
  34. console.log('After, making request to ', config.url, config.baseURL)
  35. return config;
  36. })
  37. $axios.onResponse(res => {
  38. const data = res.data;
  39. // 不跳转到login的页面reg list
  40. const excludePath = ['/user/register', '/cert/type/:id', '/type/vip/', '/cert/', '/user/:id'];
  41. const needLogin = path => {
  42. let result = true;
  43. excludePath.forEach(reg => {
  44. reg = reg.replace(/:id/, '');
  45. if (RegExp(reg).test(path)) {
  46. result = false;
  47. }
  48. })
  49. return result;
  50. }
  51. // req && req.url && needLogin(req.url)
  52. if(data.status === 1) {
  53. return res;
  54. } else if(data.status === -99) {
  55. if (req && req.url && needLogin(req.url)) {
  56. redirect('/?loginbox=show');
  57. }
  58. return res;
  59. } else {
  60. Vue.prototype.$message.error(data.info);
  61. return data;
  62. }
  63. })
  64. $axios.onError(error => {
  65. console.log('err', error);
  66. // const code = parseInt(error.response && error.response.status)
  67. // if (code === 400) {
  68. // redirect('/400')
  69. // }
  70. })
  71. }