【问题标题】:Angular Universal doesn't serve static assetsAngular Universal 不提供静态资源
【发布时间】:2022-01-13 05:01:05
【问题描述】:

我运行简单的Angular Universal SSR(服务器端渲染)应用程序,一切正常,服务器渲染html,但有一个问题。静态资产,如字体、图像、图标不会由服务器加载,而是由浏览器加载。我想做的是用静态资产渲染html。

我尝试了express.static() 功能,但无法使其工作。那我怎样才能让它工作呢?

【问题讨论】:

  • 你找到问题了吗?谢谢。

标签: node.js angular express server-side-rendering angular-universal


【解决方案1】:

通过建议 here 让它工作。

根据this article实现HTTP拦截器。它将绝对 url 添加到具有相对路径的所有请求中,因此运行服务器的 SSR 将起作用。但是虽然静态预渲染this.request 将为空,但在这种情况下,您应该将此类请求重定向到您自己的静态服务器,例如http://localhost:3000

创建用于预渲染的 NodeJs 脚本。它将在端口 3000(与拦截器中的相同端口)上运行 static server,当它运行时,您可以在 child process 中执行 npm run prerender。然后监听子进程上的事件errorclose,当它们发生时关闭服务器:

const { spawn } = require('child_process');

// In static server 'listen' callback
const sp = spawn('npm', ['run', 'prerender'], { stdio: 'inherit', timeout: 5 * 60 * 1000 })
sp.on('error', (err) => {
    // Pre-rendering failed.
    // TODO kill subprocess, close server, end current process with error code
});
sp.on('exit', (code: number) => {
  // Pre-rendering is finished
  // TODO Close server
  
  if (code !== 0) {
    // Pre-rendering failed.
    // TODO End current process with error code
  }
})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-26
    • 2018-03-16
    • 2022-10-20
    • 2019-12-13
    相关资源
    最近更新 更多