Angular 7 SSR获取ReferenceError:文档未定义



我在项目中使用Angular 7,我想将SSR(服务器端渲染(添加到我的项目中。我使用命令

ng add @nguniversal/express-engine --clientProject matngular

所以他们添加了一堆文件。然后我继续命令

npm run build:ssr 

建造成功了。所以我开始使用命令来提供dist文件夹

npm run serve:ssr

所以我得到了类似下面的错误

D:git-workspacethe-seagate-suiteseagate-webdistserver.js:205940
'function' === typeof document.createEvent ? function CustomEvent (type, params) {
^
ReferenceError: document is not defined
at Object.eventmap (D:git-workspacethe-seagate-suiteseagate-webdistserver.js:205940:23)
at __webpack_require__ (D:git-workspacethe-seagate-suiteseagate-webdistserver.js:20:30)
at Object.NativeCustomEvent (D:git-workspacethe-seagate-suiteseagate-webdistserver.js:205812:19)
at __webpack_require__ (D:git-workspacethe-seagate-suiteseagate-webdistserver.js:20:30)
at Object.<anonymous> (D:git-workspacethe-seagate-suiteseagate-webdistserver.js:205097:17)
at __webpack_require__ (D:git-workspacethe-seagate-suiteseagate-webdistserver.js:20:30)
at Module.<anonymous> (D:git-workspacethe-seagate-suiteseagate-webdistserver.js:204339:65)
at __webpack_require__ (D:git-workspacethe-seagate-suiteseagate-webdistserver.js:20:30)
at Object.ng2-dragula (D:git-workspacethe-seagate-suiteseagate-webdistserver.js:156920:18)
at __webpack_require__ (D:git-workspacethe-seagate-suiteseagate-webdistserver.js:132440:30)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! the-seagate-suite@1.0.0 serve:ssr: `node dist/server` 
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the the-seagate-suite@1.0.0 serve:ssr script.
npm ERR! This is probably not a problem with npm. There is likely additional 
logging output above.
npm ERR! A complete log of this run can be found in:
npm ERR!     C:UsersUserAppDataRoamingnpm-cache_logs2020-11- 
20T07_04_53_246Z-debug.log

我已经尝试了Stackoverflow的解决方案,接受了答案。但没有一个对我有用。我的Angular项目版本是7.3.6,typeScript是3.2.4。谢谢

Adam,

正如Angular文档所述:

由于Universal应用程序不会在浏览器中执行服务器上可能缺少浏览器API和功能。

例如,服务器端应用程序不能仅引用浏览器全局对象,如窗口、文档、导航器或位置。

Angular在这些对象上提供了一些可注入的抽象,例如作为位置或文件;它可以充分替代这些API。如果Angular没有提供它,就有可能编写新的抽象在浏览器中委托给浏览器API和在服务器上的替代实现(也称为填充(。

您可以尝试通过组件或服务的构造函数中的角度依赖注入来注入Document实例:

constructor(@Inject(DOCUMENT) private document: Document) {}

最新更新