我正在使用IIS上托管的angular4。此外,我正在使用IISnode(https://github.com/tjanczuk/iisnode)进行服务器端渲染。因此在我的 web.config 中,我制定了规则来重写所有向节点文件server.js请求,以便进行服务器端呈现。这是规则。
配置:
<rule name="Angular">
<match url="^.*$" ignoreCase="false" />
<conditions logicalGrouping="MatchAll" trackAllCaptures="false">
<add input="{REQUEST_FILENAME}" matchType="IsDirectory" ignoreCase="false" negate="true" />
<add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
</conditions>
<action type="Rewrite" url="server.js" />
</rule>
server.ts文件生成server.js文件。这是代码。
// These are important and needed before anything else
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';
// Faster server renders w/ Prod mode (dev mode never needed)
enableProdMode();
// Express server
const app = express();
const PORT = process.env.PORT || 4000;
const DIST_FOLDER = join(process.cwd(), '/');
// Our index.html we'll use as our template
const template = readFileSync(join(DIST_FOLDER,'index.html')).toString();
// * NOTE :: leave this as require() since this file is built Dynamically from webpack
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, {
// Our index.html
document: template,
url: options.req.url,
// DI so that we can get lazy-loading to work differently (since we need it to just instantly render it)
extraProviders: [
provideModuleMap(LAZY_MODULE_MAP)
]
}).then(html => {
callback(null, html);
});
});
app.set('view engine', 'html');
app.set('views', join(DIST_FOLDER));
// Server static files from /browser
app.get('*.*', express.static(join(DIST_FOLDER)));
// All regular routes use the Universal engine
app.get('*', (req, res) => {
res.render(join(DIST_FOLDER, 'index.html'), { req });
});
// Start up the Node server
app.listen(PORT, () => {
console.log(`Node server listening on http://localhost:${PORT}`);
});
问题出在所有路由上,服务器端渲染都可以。但是对于根域'/'则不能进行服务器端渲染,而普通index.html是从服务器提供的。 因此,对于所有其他路由,响应头为。
您可以看到它由ASP.NET提供支持并同时表达了两者。但是对于根域响应标头是:
仅由ASP.NET驱动。
我找不到服务器端渲染无法提供主根路由的原因。