nodejs如何根据不同的设备加载不同的前端文件

项目的前端分为移动端和pc端,然后打包后有两个文件 dist1 和 dist2
现在后端用的nodejs且移动端和pc端共用一套后端代码
原来只用pc端的时候,nodejs通过以下代码指定静态文件

app.use(express.static(path.join(__dirname, '../dist')))

现在想通过nodejs判断是移动端orPC端,然后pc端指定dist1,移动端指定dist2。这个该如何实现?

更新通过以下代码可以判断是pc还是移动端,

app.all('*', (req, res, next) => {
  const TYPE = req.headers['user-agent'].toLowerCase()
  // console.log(TYPE)
  const IS_MOBILE = TYPE.indexOf('android') > -1 || TYPE.indexOf('ios') > -1
  if (IS_MOBILE) {
    console.log('mobile')
    app.use(express.static(path.join(__dirname, '../dist2')))
  } else {
    console.log('pc')
    app.use(express.static(path.join(__dirname, '../dist')))
  }
  next()
})

但是带来一个问题,就是第一次pc端访问后,用移动端访问还是pc端的前端资源。第一次移动端访问,之后用pc端访问的还是移动端的资源。是不是node的缓存问题?

阅读 3.1k
2 个回答

最后通过 nginx 实现了
nginx 配置代码

server {
    listen       80 default_server;
    listen       [::]:80 default_server;
    server_name  www.hellomrbigbigshot.xyz;
    if ($http_host !~ "^www.hellomrbigbigshot.xyz$") {
       rewrite  ^(.*)    http://www.hellomrbigbigshot.xyz$1 permanent;
    }
    if ($http_user_agent ~* (mobile|nokia|iphone|ipad|android|samsung|htc|blackberry)) {
      rewrite  ^(.*)    http://m.hellomrbigbigshot.xyz$1 permanent;
    }

    # Load configuration files for the default server block.
    include /etc/nginx/default.d/*.conf;

    location / {
      root /var/www/pc;
      index index.html;
      try_files $uri $uri/ /index.html;
    }
    location /api {
      rewrite  ^/apis/(.*)$ /$1 break;
      proxy_pass http://xxx.xx.xxx.xx:8081/api;
    }

    error_page 404 /404.html;
        location = /40x.html {
    }

    error_page 500 502 503 504 /50x.html;
        location = /50x.html {
    }
}
server {
  listen       80;
  server_name  m.hellomrbigbigshot.xyz;
  if ($http_user_agent !~* (mobile|nokia|iphone|ipad|android|samsung|htc|blackberry)) {
      rewrite  ^(.*)    http://www.hellomrbigbigshot.xyz$1 permanent;
  }

  location / {
    root /var/www/mobile;
    index index.html;
    try_files $uri $uri/ /index.html;
  }
  location /api {
    rewrite  ^/apis/(.*)$ /$1 break;
    proxy_pass http://xxx.xx.xxx.xx:8081/api;
  }
  error_page 404 /404.html;
      location = /40x.html {
  }

  error_page 500 502 503 504 /50x.html;
      location = /50x.html {
  }
}
if (!require('is-mobile')()) {
    app.use(express.static(path.join(__dirname, '../dist1')))
} else {
    app.use(express.static(path.join(__dirname, '../dist2')))
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题