setup.global.js 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. export default async function (to, from) {
  2. //获得全局url
  3. const { $webUrl, $CwebUrl } = useNuxtApp();
  4. if(to.path == '/' || to.path == '/404'){
  5. //如果目标路由是/,或者/404 无需验证
  6. }else{
  7. // to是目标路由对象,from是来源路由对象
  8. console.log('进入路由中间件,目标路由:', to.path,"当前路由:",from.path);
  9. //拆分目标路由
  10. let parts = parseRoute(to.path)
  11. console.log(parts)
  12. const responseRoute = await $fetch($webUrl + '/web/checkWebsiteRoute', {
  13. headers: {
  14. 'Content-Type': 'application/json',
  15. 'Userurl': $CwebUrl,
  16. 'Origin': $CwebUrl
  17. },
  18. query: parts
  19. })
  20. console.log(responseRoute)
  21. if(responseRoute.code == 200){
  22. //如果路由存在,不做任何操作
  23. }else{
  24. return navigateTo('/404')
  25. }
  26. }
  27. }
  28. //提取路由
  29. function parseRoute(url) {
  30. const parts = url.split('/').filter(Boolean); // 分割并过滤空字符串
  31. const lastPart = parts[parts.length - 1];
  32. // 提取 id(数字.html 的数字部分)
  33. const idMatch = lastPart.match(/^(\d+)\.html$/);
  34. const id = idMatch ? idMatch[1] : undefined;
  35. // 如果最后是数字.html、index.html 或 list-数字.html,则去掉它
  36. const isSpecialRoute = idMatch || lastPart === "index.html" || lastPart.startsWith("list-");
  37. if (isSpecialRoute) {
  38. parts.pop();
  39. }
  40. let all_route, last_route;
  41. // 如果路径以 xiangcunshangcheng 开头
  42. if (parts[0] === "xiangcunshangcheng") {
  43. if( parts.length > 1){
  44. if(parts[parts.length - 1] != 'gongying' && parts[parts.length - 1] != 'qiugou'){
  45. // 否则按原逻辑处理
  46. all_route = parts.join('/');
  47. last_route = parts.length > 0 ? parts[parts.length - 1] : null;
  48. }else{
  49. // all_route = 去掉最后一层
  50. all_route = parts.slice(0, -1).join('/');
  51. // last_route = 新的最后一层
  52. last_route = parts.length > 1 ? parts[parts.length - 2] : null;
  53. }
  54. }else{
  55. // 否则按原逻辑处理
  56. all_route = parts.join('/');
  57. last_route = parts.length > 0 ? parts[parts.length - 1] : null;
  58. }
  59. } else {
  60. // 否则按原逻辑处理
  61. all_route = parts.join('/');
  62. last_route = parts.length > 0 ? parts[parts.length - 1] : null;
  63. }
  64. // 返回结果(只有数字.html 时才包含 id)
  65. const result = {
  66. all_route,
  67. last_route
  68. };
  69. if (id !== undefined) {
  70. result.id = id;
  71. }
  72. return result;
  73. }