middleware.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. // 遵守pc与移动的命名规范,移动端前面加 m.,就会自动拼接拦截路径,自动响应式匹配pc/移动
  2. const mobilepath = [
  3. '/user/m_user',
  4. ]
  5. const pcpath = [
  6. '/pages/m.index.vue',
  7. ]
  8. export default function ({ isServer, req, redirect, route }) {
  9. // 这两个只有不同项目不同端口才用得上
  10. // let pcOrigin = 'http://sincelocal.aupup.com:9003'
  11. // let mobileOrigin = 'http://sincelocal.aupup.com:9004'
  12. let isMobile = ua => {
  13. return !!ua.match(/AppleWebKit.*Mobile.*/)
  14. }
  15. let userAgent = req ? req.headers['user-agent'] : navigator.userAgent || ''
  16. if(!req) return
  17. // http不能直接写死,要取出来,可能是https
  18. const request=req?.headers?.referer?.split('://')[0]||'http';
  19. // console.log(request,'当前的请求头');
  20. // 如果是移动端,但是确访问了pc的路径
  21. if (isMobile(userAgent) && pcpath.includes(route.path.toLowerCase())) {
  22. console.log('重定向到移动端', req.headers.host, route.fullPath)
  23. return redirect(
  24. `${request}://${req.headers.host}` +
  25. `/m.${route.fullPath.substring(1, route.fullPath.length)}`
  26. )
  27. } else if (
  28. !isMobile(userAgent) &&
  29. mobilepath.includes(route.path.toLowerCase())
  30. ) {
  31. // 如果是pc进了移动
  32. // 重定向到pc端
  33. console.log('重定向到PC端', req.headers.host, route.fullPath)
  34. return redirect(
  35. `${request}://${req.headers.host}` +
  36. `/${route.fullPath.substring(3, route.fullPath.length)}`
  37. )
  38. }
  39. // return isMobile(userAgent) ? '' : redirect(pcOrigin + route.fullPath)
  40. // 使用redirect 重定向到外链需要加上前缀:http / https
  41. }