当前位置: 首页 > 知识库问答 >
问题:

为什么Angular Universal Server端渲染在Firebase主机部署后会出现错误?

微生嘉祥
2023-03-14

我目前正在使用Angular的第三方库(如Angular CLI/Angular Universal)开发Angular,下面的链接是https://github.com/Angular/Angulal-cli/wiki/stories-Universal-rendering/和firebase hosting/以及实时数据库。它在我的本地机器上工作得很好,localhost:4000。我看到它呈现的服务器端呈现流畅,我看到HTML我需要的SEO友好,我还使用惰性加载,提高了web应用程序性能的加载速度非常快。现在,我的问题是,在我使用通用服务器端渲染部署Angular应用程序后,也使用惰性加载。我得到这样一个错误:错误:不能处理请求,如果我只是部署而没有延迟加载,我得到这3个错误,

1. Uncaught SyntaxError: Unexpected token < inline.318b50c57b4eba3d437b.bundle.js:1 

2. Uncaught SyntaxError: Unexpected token < polyfills.bf95165a1d5098766b92.bundle.js:1

3. Uncaught SyntaxError: Unexpected token < main.4871dfc6be55ccbf4c0b.bundle.js:1 

下面是文件夹结构:

>

  • dist=>这是angular应用程序的构建文件夹

    • 浏览器
    • 服务器
    • server.js
      null
      null
      null
    import { BrowserModule } from '@angular/platform-browser';
    import { NgModule } from '@angular/core';
    
    import { Routes, RouterModule } from '@angular/router';
    
    import { AppComponent } from './app.component';
    
    import { ButtonsComponent } from './demo/buttons/buttons.component';
    
    const routes: Routes = [
      { path: 'buttons', loadChildren: './demo/demo.module#DemoModule' },
      { path: '**', redirectTo: 'buttons' }
    ];
    
    @NgModule({
      declarations: [
        AppComponent
      ],
      imports: [
        BrowserModule.withServerTransition({ appId: 'something-unique-id' }),
        RouterModule.forRoot(routes)
      ],
      providers: [],
      bootstrap: [
        AppComponent,
        ButtonsComponent
      ]
    })
    
    export class AppModule { }
    

    src/app/app.server.module.ts

     import {NgModule} from '@angular/core';
        import {ServerModule} from '@angular/platform-server';
        import {ModuleMapLoaderModule} from '@nguniversal/module-map-ngfactory-loader';
    
        import {AppModule} from './app.module';
        import {AppComponent} from './app.component';
    
        @NgModule({
          imports: [
            // The AppServerModule should import your AppModule followed
            // by the ServerModule from @angular/platform-server.
            AppModule,
            ServerModule, 
            ModuleMapLoaderModule // <-- *Important* to have lazy-loaded routes work
          ],
          // Since the bootstrapped component is not inherited from your
          // imported AppModule, it needs to be repeated here.
          bootstrap: [AppComponent],
        })
        export class AppServerModule {}
    

    src/main.server.ts

    export { AppServerModule } from './app/app.server.module';
    

    src/tsconfig.server.json

    {
      "extends": "../tsconfig.json",
      "compilerOptions": {
        "outDir": "../out-tsc/app",
        "baseUrl": "./",
        // Set the module format to "commonjs":
        "module": "commonjs",
        "types": []
      },
      "exclude": [
        "test.ts",
        "**/*.spec.ts"
      ],
      // Add "angularCompilerOptions" with the AppServerModule you wrote
      // set as the "entryModule".
      "angularCompilerOptions": {
        "entryModule": "app/app.server.module#AppServerModule"
      }
    }
    
    {
      "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
      "project": {
        "name": "kuntento"
      },
      "apps": [
        {
          "root": "src",
          "outDir": "dist/browser",
          "assets": [
            "assets",
            "favicon.ico"
          ],
          "index": "index.html",
          "main": "main.ts",
          "polyfills": "polyfills.ts",
          "test": "test.ts",
          "tsconfig": "tsconfig.app.json",
          "testTsconfig": "tsconfig.spec.json",
          "prefix": "app",
          "styles": [
            "styles.css"
          ],
          "scripts": [],
          "environmentSource": "environments/environment.ts",
          "environments": {
            "dev": "environments/environment.ts",
            "prod": "environments/environment.prod.ts"
          }
        },
        {
          "platform": "server",
          "root": "src",
          "outDir": "dist/server",
          "assets": [
            "assets",
            "favicon.ico"
          ],
          "index": "index.html",
          "main": "main.server.ts",
          "test": "test.ts",
          "tsconfig": "tsconfig.server.json",
          "testTsconfig": "tsconfig.spec.json",
          "prefix": "app",
          "styles": [
            "styles.css"
          ],
          "scripts": [],
          "environmentSource": "environments/environment.ts",
          "environments": {
            "dev": "environments/environment.ts",
            "prod": "environments/environment.prod.ts"
          }
        }
      ],
      "e2e": {
        "protractor": {
          "config": "./protractor.conf.js"
        }
      },
      "lint": [
        {
          "project": "src/tsconfig.app.json",
          "exclude": "**/node_modules/**"
        },
        {
          "project": "src/tsconfig.spec.json",
          "exclude": "**/node_modules/**"
        },
        {
          "project": "e2e/tsconfig.e2e.json",
          "exclude": "**/node_modules/**"
        }
      ],
      "test": {
        "karma": {
          "config": "./karma.conf.js"
        }
      },
      "defaults": {
        "styleExt": "css",
        "component": {}
      }
    }
    
        import 'zone.js/dist/zone-node';
        import 'reflect-metadata';
    
        import { renderModuleFactory } from '@angular/platform-server';
        import { enableProdMode } from '@angular/core';
    
        import * as express from 'express';
        import { join } from 'path';
        import { readFileSync } from 'fs';
    
        enableProdMode();
    
        const app = express();
    
        const PORT = process.env.PORT || 4000;
        const DIST_FOLDER = join(process.cwd(), 'dist');
    
        const template = readFileSync(join(DIST_FOLDER, 'browser', 'index.html')).toString();
    
        const { AppServerModuleNgFactory, LAZY_MODULE_MAP } = require('./dist/server/main.bundle');
    
        const { provideModuleMap } = require('@nguniversal/module-map-ngfactory-loader');
    
        app.engine('html', (_, options, callback) => {
            renderModuleFactory(AppServerModuleNgFactory, {
                document: template,
                url: options.req.url,
                extraProviders: [
                    provideModuleMap(LAZY_MODULE_MAP)
                ]
            }).then(html => {
                callback(null, html);
            });
        });
    
        app.set('view engine', 'html');
        app.set('views', join(DIST_FOLDER, 'browser'));
    
        app.get('*.*', express.static(join(DIST_FOLDER, 'browser')));
    
        app.get('*', (req, res) => {
            res.render(join(DIST_FOLDER, 'browser', 'index.html'), { req });
        });
    
        app.listen(PORT, () => {
            console.log(`Node server listening on http://localhost:${PORT}`);
        });
    
    FOR, ./webpack.server.config.js
    
    const path = require('path');
    const webpack = require('webpack');
    
    module.exports = {
        entry: { server: './server.ts' },
        resolve: { extensions: ['.js', '.ts'] },
        target: 'node',
        externals: [/(node_modules|main\..*\.js)/],
        output: {
            path: path.join(__dirname, 'dist'),
            filename: '[name].js'
        },
        module: {
            rules: [
                { test: /\.ts$/, loader: 'ts-loader' }
            ]
        },
        plugins: [
            new webpack.ContextReplacementPlugin(
                /(.+)?angular(\\|\/)core(.+)?/,
                path.join(__dirname, 'src'),
                {}
            ),
            new webpack.ContextReplacementPlugin(
                /(.+)?express(\\|\/)(.+)?/,
                path.join(__dirname, 'src'),
                {}
            )
        ]
    }
    
    {
      "name": "universalrendering",
      "version": "0.0.0",
      "license": "MIT",
      "scripts": {
        "ng": "ng",
        "start": "ng serve",
        "build": "ng build --prod",
        "build:ssr": "npm run build:client-and-server-bundles && npm run webpack:server",
        "serve:ssr": "node dist/server.js",
        "build:client-and-server-bundles": "ng build --prod && ng build --prod --app 1 --output-hashing=false",
        "webpack:server": "webpack --config webpack.server.config.js --progress --colors",
        "test": "ng test",
        "lint": "ng lint",
        "e2e": "ng e2e"
      },
      "private": true,
      "dependencies": {
        "@angular/animations": "^5.2.0",
        "@angular/common": "^5.2.0",
        "@angular/compiler": "^5.2.0",
        "@angular/core": "^5.2.0",
        "@angular/forms": "^5.2.0",
        "@angular/http": "^5.2.0",
        "@angular/platform-browser": "^5.2.0",
        "@angular/platform-browser-dynamic": "^5.2.0",
        "@angular/platform-server": "^5.2.6",
        "@angular/router": "^5.2.0",
        "@nguniversal/module-map-ngfactory-loader": "^5.0.0-beta.5",
        "angular-universal-express-firebase": "0.0.4",
        "core-js": "^2.4.1",
        "express": "^4.16.2",
        "firebase-functions": "^0.8.1",
        "rxjs": "^5.5.6",
        "ts-loader": "^3.5.0",
        "zone.js": "^0.8.19"
      },
      "devDependencies": {
        "@angular/cli": "^1.7.1",
        "@angular/compiler-cli": "^5.2.0",
        "@angular/language-service": "^5.2.0",
        "@types/jasmine": "~2.8.3",
        "@types/jasminewd2": "~2.0.2",
        "@types/node": "~6.0.60",
        "codelyzer": "^4.0.1",
        "jasmine-core": "~2.8.0",
        "jasmine-spec-reporter": "~4.2.1",
        "karma": "~2.0.0",
        "karma-chrome-launcher": "~2.2.0",
        "karma-coverage-istanbul-reporter": "^1.2.1",
        "karma-jasmine": "~1.1.0",
        "karma-jasmine-html-reporter": "^0.2.2",
        "protractor": "~5.1.2",
        "ts-node": "~4.1.0",
        "tslint": "~5.9.1",
        "typescript": "^2.7.2"
      }
    }
    

    这是针对Firebase主机的:

    • 服务器转接器

    对于,index.html

    import * as functions from 'firebase-functions';
    import * as angularUniversal from 'angular-universal-express-firebase';
    
    export let server_rendering = angularUniversal.trigger({
        index: __dirname + '/browser/index.html',
        main: __dirname + '/server/main.bundle',
        enableProdMode: true,
        browserCacheExpiry: 1200,
        cdnCacheExpiry: 600
    });
    
    {
        "compilerOptions": {
            "module": "commonjs",
            "target": "es2015",
            "rootDir": ".",
            "outDir": "../functions"
        },
        "files": [
            "index.ts"
        ]
    }
    
      null

    FOR,package.json

    {
      "name": "functions",
      "description": "Cloud Functions for Firebase",
      "scripts": {
        "lint": "./node_modules/.bin/eslint .",
        "serve": "firebase serve --only functions",
        "shell": "firebase experimental:functions:shell",
        "start": "npm run shell",
        "deploy": "firebase deploy --only functions",
        "logs": "firebase functions:log"
      },
      "dependencies": {
        "firebase-admin": "~5.8.1",
        "firebase-functions": "^0.8.1",
        "@angular/animations": "^5.2.0",
        "@angular/common": "^5.2.0",
        "@angular/compiler": "^5.2.0",
        "@angular/core": "^5.2.0",
        "@angular/forms": "^5.2.0",
        "@angular/http": "^5.2.0",
        "@angular/platform-browser": "^5.2.0",
        "@angular/platform-browser-dynamic": "^5.2.0",
        "@angular/platform-server": "^5.2.6",
        "@angular/router": "^5.2.0",
        "@nguniversal/module-map-ngfactory-loader": "^5.0.0-beta.5",
        "angular-universal-express-firebase": "0.0.4",
        "core-js": "^2.4.1",
        "express": "^4.16.2",
        "rxjs": "^5.5.6",
        "ts-loader": "^3.5.0",
        "zone.js": "^0.8.19"
      },
      "devDependencies": {
        "eslint": "^4.12.0",
        "eslint-plugin-promise": "^3.6.0"
      },
      "private": true
    }
    

    对于,index.js

    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    const angularUniversal = require("angular-universal-express-firebase");
    exports.server_rendering = angularUniversal.trigger({
        index: __dirname + '/browser/index.html',
        main: __dirname + '/server/main.bundle',
        enableProdMode: true,
        browserCacheExpiry: 1200,
        cdnCacheExpiry: 600
    });
    
  • 共有1个答案

    微生信鸿
    2023-03-14

    请在这里检查相同的问题,通常是当重定向规则发送索引页而不是JavaScript时出现的错误。

    更新package.json脚本,如下所示:

            "scripts": {
              "ng": "ng",
              "start": "ng serve",
              "build": "ng build --prod",
              "build.server": "ng build -aot -app ssr",
              "test": "ng test",
              "lint": "ng lint",
              "e2e": "ng e2e"
            },
    

    然后.angull-cli.json“main”:“main.ts”“main”:“main.server.ts”

    npm run build
    npm run build.server
    

    请查看教程到这里部署角通用W/Firebase和演示。

    希望这对你有帮助!!

     类似资料:
    • 当我试图从netbean部署我的web应用程序时,我得到以下错误: 那是什么?为什么我会犯这个错误? 以下是来自的代码片段: 以下是netbeans服务器设置中的快照:

    • 我正在尝试使用Minikube、Docker注册表和演示节点项目创建本地库伯内特斯部署。 我做的第一件事是安装Docker v1.12.3,然后是Minikube v0.12.2。 然后,我通过运行这个命令创建了一个Docker注册表容器(通过本教程,只运行下面的第一个命令) 接下来,我运行这个minikube命令来创建本地kubernetes集群: 我的项目结构如下所示: 我的Dockerfil

    • 我正在使用Laravel 5.1 要摆脱公共文件夹: > 移动根目录中的所有公用文件夹内容。 已更改

    • 问题内容: 我正在尝试使用Minikube,Docker Registry和演示节点项目创建本地Kubernetes部署。 我做的第一件事是安装Docker v1.12.3,然后是Minikube v0.12.2。 然后我通过运行此命令创建了一个Docker Registry容器(通过本教程,仅运行下面的第一个命令) 接下来,我运行此minikube命令以创建本地kubernetes集群: 我的项

    • 错误:第 1 行的解析错误:函数搜索(sour ^ 期望“字符串”、“数字”、“空”、“真”、“假”、“{”、“[”,得到“未定义” 代码:

    • 我实现了以下REST调用: 也是一个提供和使用application/x-protobuf的提供者类: 我的pom。xml看起来像: 我的小部件。原型: 选项java_package=“example”;选项java\u outer\u classname=“WidgetsProtoc”; 对于http://localhost:8080/RESTfulExample/widgets我得到以下错误消