nuxtAxios.js 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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. // config.headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8';
  20. const data = config.data;
  21. // const cookie = config.headers.cookie || config.headers.common.cookie || '';
  22. let formData = '';
  23. for(const key in data) {
  24. if(data.hasOwnProperty(key)) {
  25. const element = data[key];
  26. formData += `${key}=${element}&`;
  27. }
  28. }
  29. // formData += cookie.split(';').join('&');
  30. config.data = formData;
  31. // config.data = qs.stringify(config.data);
  32. }
  33. console.log('After, making request to ', config.url, config.baseURL)
  34. return config;
  35. })
  36. $axios.onResponse(res => {
  37. const data = res.data;
  38. // 不跳转到login的页面reg list
  39. const excludePath = ['/user/register', '/cert/type/:id', '/type/vip/', '/cert/', '/user/:id'];
  40. const needLogin = path => {
  41. let result = true;
  42. excludePath.forEach(reg => {
  43. reg = reg.replace(/:id/, '');
  44. if (RegExp(reg).test(path)) {
  45. result = false;
  46. }
  47. })
  48. return result;
  49. }
  50. req && req.url && needLogin(req.url)
  51. if(data.status === 1) {
  52. return res;
  53. } else if(data.status === -99) {
  54. if (req && req.url && needLogin(req.url)) {
  55. redirect('/?loginbox=show');
  56. }
  57. return res;
  58. } else {
  59. return res;
  60. }
  61. })
  62. $axios.onError(error => {
  63. console.log('err', error);
  64. // const code = parseInt(error.response && error.response.status)
  65. // if (code === 400) {
  66. // redirect('/400')
  67. // }
  68. })
  69. }