金币系统前端
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

44 lines
1.8 KiB

5 months ago
5 months ago
5 months ago
5 months ago
  1. import axios from 'axios';
  2. export default function (options) {
  3. //配置每次发送请求都从localStorage中获取名字叫token的数据,
  4. //添加到请求头部的Authorization属性中
  5. const token = localStorage.getItem('token');
  6. //Object.assign用于合并对象的数据
  7. options.data.token = token;
  8. // options.headers = Object.assign(
  9. // { token: token },
  10. // options.headers || {}
  11. // );
  12. //axios() 返回一个promise对象,用于异步请求
  13. //options是一个对象,其中包含了许多用于配置请求的参数,
  14. //例如请求的url、请求方法(GET、POST等)、请求头等
  15. return axios(options)
  16. .then(({ status, data, statusText }) => {
  17. //该函数在请求成功并返回数据时被调用
  18. //status:HTTP状态码,例如200表示请求成功。
  19. //data:服务器返回的数据。
  20. // statusText:HTTP状态文本,例如"OK"表示请求成功。
  21. // console.log(data);
  22. if (status == 200) {
  23. return data;
  24. } else {
  25. throw new e(statusText);
  26. }
  27. })
  28. .catch(e=>{
  29. // 检查是否是因为token过期导致的401错误
  30. if (e.response && e.response.status === 401) {
  31. // 清除localStorage中的token
  32. localStorage.removeItem('token');
  33. // // 执行重新登录的逻辑,例如跳转到登录页面
  34. window.location.href = '/login';
  35. // 可以在这里返回一个特定的值或者对象,以便调用者知道需要重新登录
  36. return { needsLogin: true };
  37. } else {
  38. // 其他类型的错误,直接抛出
  39. return Promise.reject(e);
  40. }
  41. });
  42. }