将我的应用程序迁移到 Angular Universal 后,我遇到了同样的问题。除了根页面未在服务器端呈现之外,一切正常。
在谷歌搜索和注释掉我的服务器脚本的某些部分后,我意识到我忘记在迁移之前删除为 Angular 应用程序提供服务的行。
这是我的代码:
import 'zone.js/dist/zone-node';
import 'reflect-metadata';
import * as express from "express";
import * as helmet from "helmet";
import * as path from "path";
import * as favicon from "serve-favicon";
import * as bodyParser from "body-parser";
import {ngExpressEngine} from "@nguniversal/express-engine";
import {provideModuleMap} from "@nguniversal/module-map-ngfactory-loader";
import {enableProdMode} from "@angular/core";
enableProdMode();
const app = express();
// config
app.use(helmet());
app.use(favicon(path.join(__dirname, '../../favicon.ico')));
app.use(bodyParser.json({limit: "50mb"}));
app.use(bodyParser.urlencoded({limit: "50mb", extended: true}));
app.use(express.static(path.join(__dirname, "../../dist/frontend/browser"))); // <- statically serving the Angular app
const {AppServerModuleNgFactory, LAZY_MODULE_MAP} = require(path.join(__dirname, "../../dist/frontend/server/main"));
// rendering engine (angular universal)
app.engine('html', ngExpressEngine({
bootstrap: AppServerModuleNgFactory,
providers: [
provideModuleMap(LAZY_MODULE_MAP)
]
}));
app.set('view engine', 'html');
app.set('views', path.join(__dirname, "../../dist/frontend/browser"));
// routing
app.use(express.static(path.join(__dirname, "../../public")));
app.use("/api", require("./routes/api"));
app.use("/images", require("./routes/images"));
app.get('*.*', express.static(path.join(__dirname, "../../dist/frontend/browser"), {
maxAge: '1d'
}));
app.get('/*', (req, res) => {
res.render('index', {req, res}, (err, html) => {
if (html) {
res.send(html);
} else {
console.error(err);
res.send(err);
}
});
});
module.exports = app;
删除app.use(express.static(path.join(__dirname, "../../dist/frontend/browser"))); 后,Universal 现在可以毫无问题地渲染根页面。