nuxtAxios.js 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. import qs from 'qs';
  2. export default function ({ $axios, redirect, req, ...args }) {
  3. $axios.onRequest(config => {
  4. config.headers['Content-Type'] = 'application/x-www-form-urlencoded';
  5. console.log('Before, making request to ', config.url, config.baseURL)
  6. const referer = config.headers.common && config.headers.common.referer;
  7. const url = config.url;
  8. if (referer && !(/https?/.test(url))) {
  9. // server http
  10. config.url = referer.split('/').slice(0, 3).join('/') + url;
  11. config.baseURL = referer.split('/').slice(0, 3).join('/');
  12. } else {
  13. // client http
  14. config.url = /https?/.test(url) ? `/${url.split('/').slice(3).join('/')}` : url;
  15. config.baseURL = '';
  16. }
  17. // stringify post data
  18. if (config.method === 'post') {
  19. console.log(config);
  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. return res;
  61. }
  62. })
  63. $axios.onError(error => {
  64. console.log('err', error);
  65. // const code = parseInt(error.response && error.response.status)
  66. // if (code === 400) {
  67. // redirect('/400')
  68. // }
  69. })
  70. }