Vue SSR 报警 The client-side rendered virtual DOM tree is not matching server-rendered con

接手前人留下来的 vue server side rendering 官网项目,访问测服路径时控制台报警

[Vue warn]: The client-side rendered virtual DOM tree is not matching server-rendered content. This is likely caused by incorrect HTML markup, for example nesting block-level elements inside <p>, or missing <tbody>. Bailing hydration and performing full client-side render.

而官网的 SSR 渲染是根据进来的 hostname 是哪个而决定渲染哪个页面。出了的这个问题意味着 SSR 服务端渲染的页面内容,和前端客户端渲染时页面不一致。

我在 node render 的部分打印返回

const render = (req, res) => {
  // ......
  console.log('~~打印了~~~origin: ', origin, ' hostname: ' + req.hostname, ' host: ' + req.host)
  renderer.renderToString(context, (err, html) => {
    // ......
  })
}

访问 mctalk-test.netease.im 得到的是

~~打印了~~~origin:  http://mctalk-test.netease.im  hostname: home.netease.im  host: home.netease.im

震惊,居然 origin 和 hostname 不一样。肯定是 nginx 转发过来的锅了,我找到 nginx 配置

server {
  server_name home.netease.im mctalk-test.netease.im;

  listen 80;

  proxy_set_header X-Forwarded-For  $remote_addr;
  proxy_set_header X-Real-IP  $remote_addr;
  proxy_set_header X-Forwarded-Host $server_name;
  proxy_set_header Host $host;
  proxy_set_header X-Request-Host $host;


  location / {
    # ... 跳转配置略
  }
}

绕了两圈我才回过神,大概就是上文的 $host 变量出了问题搞得。

所以把 nginx 配置拆开就更解决了

server {
  server_name home.netease.im;

  listen 80;

  proxy_set_header X-Forwarded-For  $remote_addr;
  proxy_set_header X-Real-IP  $remote_addr;
  proxy_set_header X-Forwarded-Host $server_name;
  proxy_set_header Host $host;
  proxy_set_header X-Request-Host $host;


  location / {
    # ... 跳转配置略
  }
}
server {
  server_name mctalk-test.netease.im;

  listen 80;

  proxy_set_header X-Forwarded-For  $remote_addr;
  proxy_set_header X-Real-IP  $remote_addr;
  proxy_set_header X-Forwarded-Host $server_name;
  proxy_set_header Host $host;
  proxy_set_header X-Request-Host $host;


  location / {
    # ... 跳转配置略
  }
}

重启 nginx 后再次访问 mctalk-test.netease.im 得到的是

~~打印了~~~origin:  http://mctalk-test.netease.im  hostname: mctalk-test.netease.im  host: mctalk-test.netease.im

渲染也正确了。

posted @ 2021-03-10 11:30  Ever-Lose  阅读(2824)  评论(1编辑  收藏  举报