发送后无法设置 headers。 Angular 通用 ExpressJS
Can't set headers after they are sent. Angular Universal ExpressJS
我想 return 我的组件在 Angular 5 中出现服务器端渲染的 404 错误。
在我的 server.js 我有:
app.engine('html', (_, options, callback) => {
let engine = ngExpressEngine({
bootstrap: AppServerModuleNgFactory,
providers: [
{ provide: 'response', useFactory: () => options.req.res, deps: [] },
provideModuleMap(LAZY_MODULE_MAP)
]
});
engine(_, options, callback);
});
在我的组件中:
constructor(@Inject(PLATFORM_ID) private platformId: Object, private injector: Injector) {
}
ngOnInit() {
if (showError404 && isPlatformServer(this.platformId)) {
const res = this.injector.get('response');
console.error('NOT FOUND PAGE');
const STATIC_FOLDER = join(process.cwd(), 'static_files');
res.status(404).sendFile(`${STATIC_FOLDER}/404.html`);
}
}
这是我的 server.ts 文件
import 'zone.js/dist/zone-node';
import 'reflect-metadata';
import { enableProdMode } from '@angular/core';
import * as express from 'express';
import { join } from 'path';
import * as compression from 'compression';
import * as serveStatic from 'serve-static';
import * as xml from 'xml';
import * as fs from 'fs';
import * as url from 'url';
// Faster server renders w/ Prod mode (dev mode never needed)
enableProdMode();
// Express server
const app = express();
const PORT = process.env.PORT || 4200;
const DIST_FOLDER = join(process.cwd(), 'dist');
const STATIC_FOLDER = join(process.cwd(), 'static_files');
// * NOTE :: leave this as require() since this file is built Dynamically from webpack
const { AppServerModuleNgFactory, LAZY_MODULE_MAP } = require('./dist/server/main.bundle');
// Express Engine
import { ngExpressEngine } from '@nguniversal/express-engine';
// Import module map for lazy loading
import { provideModuleMap } from '@nguniversal/module-map-ngfactory-loader';
app.use(compression({ level: 9 }));
app.get('/*', function (req, res, next) {
if (req.headers.host.match(/^www/) !== null) {
res.redirect(301, 'https://' + req.headers.host.replace(/^www\./, '') + req.url);
} else {
next();
}
});
app.get('/sitemap.xml', function (req, res, next) {
const file = `${STATIC_FOLDER}/sitemap.xml`;
fs.exists(file, function (exists) {
if (exists) {
res.sendFile(file);
}
else {
res.status(404).send('404');
}
});
});
app.get('/sitemaps/*', function (req, res, next) {
const file = `${STATIC_FOLDER}/sitemaps/${url.parse(req.url).pathname.split('/').pop()}`;
fs.exists(file, function (exists) {
if (exists) {
res.sendFile(file);
}
else {
res.status(404).send('404');
}
});
});
app.get('/robots.txt', function (req, res, next) {
const file = `${STATIC_FOLDER}/robots.txt`;
fs.exists(file, function (exists) {
if (exists) {
res.sendFile(file);
}
else {
res.status(404).send('404');
}
});
});
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET');
res.header('Access-Control-Max-Age', '3600');
res.header('Access-Control-Allow-Headers', 'Content-Type');
return next();
});
app.engine('html', (_, options, callback) => {
let engine = ngExpressEngine({
bootstrap: AppServerModuleNgFactory,
providers: [
{ provide: 'response', useFactory: () => options.req.res, deps: [] },
provideModuleMap(LAZY_MODULE_MAP)
]
});
engine(_, options, callback);
});
app.set('view engine', 'html');
app.set('views', join(DIST_FOLDER, 'browser'));
// serve static file from 'dist/browser'
app.get('*.*', express.static(join(DIST_FOLDER, 'browser'), {
maxAge: '30d'
}));
// All regular routes use the Universal engine
app.get('*', (req, res) => {
res.setHeader('Cache-Control', 'max-age=0, private, must-revalidate');
res.render(join(DIST_FOLDER, 'browser', 'index.html'), { req });
});
// Start up the Node server
app.listen(PORT, () => {
console.log(`Node server listening on http://localhost:${PORT}`);
});
应用运行正常,但服务器日志错误:
发送后无法设置headers。
有什么可以帮助我的吗?
我不太了解 ngExpressEngine,但我认为问题在于它会在您发送文件后尝试设置 headers
也许尝试使用 custom callback 这样你就不会发送任何东西我已经为 404 发送了一些东西。
app.get('*', (req, res) => {
res.setHeader('Cache-Control', 'max-age=0, private, must-revalidate');
res.render(join(DIST_FOLDER, 'browser', 'index.html'),
{ req },
(err: Error, html: string) => {
if(res.statusCode != 404 )
res.status(html ? 200 : 500).send(html || err.message);
}
);
});
另一种选择是在您的组件中将状态代码设置为 404,然后如果状态为 404,则从 express 发送文件
(err: Error, html: string) => {
if(res.statusCode != 404 )
res.status(html ? 200 : 500).send(html || err.message);
else res.send('404.html')
}
我想 return 我的组件在 Angular 5 中出现服务器端渲染的 404 错误。
在我的 server.js 我有:
app.engine('html', (_, options, callback) => {
let engine = ngExpressEngine({
bootstrap: AppServerModuleNgFactory,
providers: [
{ provide: 'response', useFactory: () => options.req.res, deps: [] },
provideModuleMap(LAZY_MODULE_MAP)
]
});
engine(_, options, callback);
});
在我的组件中:
constructor(@Inject(PLATFORM_ID) private platformId: Object, private injector: Injector) {
}
ngOnInit() {
if (showError404 && isPlatformServer(this.platformId)) {
const res = this.injector.get('response');
console.error('NOT FOUND PAGE');
const STATIC_FOLDER = join(process.cwd(), 'static_files');
res.status(404).sendFile(`${STATIC_FOLDER}/404.html`);
}
}
这是我的 server.ts 文件
import 'zone.js/dist/zone-node';
import 'reflect-metadata';
import { enableProdMode } from '@angular/core';
import * as express from 'express';
import { join } from 'path';
import * as compression from 'compression';
import * as serveStatic from 'serve-static';
import * as xml from 'xml';
import * as fs from 'fs';
import * as url from 'url';
// Faster server renders w/ Prod mode (dev mode never needed)
enableProdMode();
// Express server
const app = express();
const PORT = process.env.PORT || 4200;
const DIST_FOLDER = join(process.cwd(), 'dist');
const STATIC_FOLDER = join(process.cwd(), 'static_files');
// * NOTE :: leave this as require() since this file is built Dynamically from webpack
const { AppServerModuleNgFactory, LAZY_MODULE_MAP } = require('./dist/server/main.bundle');
// Express Engine
import { ngExpressEngine } from '@nguniversal/express-engine';
// Import module map for lazy loading
import { provideModuleMap } from '@nguniversal/module-map-ngfactory-loader';
app.use(compression({ level: 9 }));
app.get('/*', function (req, res, next) {
if (req.headers.host.match(/^www/) !== null) {
res.redirect(301, 'https://' + req.headers.host.replace(/^www\./, '') + req.url);
} else {
next();
}
});
app.get('/sitemap.xml', function (req, res, next) {
const file = `${STATIC_FOLDER}/sitemap.xml`;
fs.exists(file, function (exists) {
if (exists) {
res.sendFile(file);
}
else {
res.status(404).send('404');
}
});
});
app.get('/sitemaps/*', function (req, res, next) {
const file = `${STATIC_FOLDER}/sitemaps/${url.parse(req.url).pathname.split('/').pop()}`;
fs.exists(file, function (exists) {
if (exists) {
res.sendFile(file);
}
else {
res.status(404).send('404');
}
});
});
app.get('/robots.txt', function (req, res, next) {
const file = `${STATIC_FOLDER}/robots.txt`;
fs.exists(file, function (exists) {
if (exists) {
res.sendFile(file);
}
else {
res.status(404).send('404');
}
});
});
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET');
res.header('Access-Control-Max-Age', '3600');
res.header('Access-Control-Allow-Headers', 'Content-Type');
return next();
});
app.engine('html', (_, options, callback) => {
let engine = ngExpressEngine({
bootstrap: AppServerModuleNgFactory,
providers: [
{ provide: 'response', useFactory: () => options.req.res, deps: [] },
provideModuleMap(LAZY_MODULE_MAP)
]
});
engine(_, options, callback);
});
app.set('view engine', 'html');
app.set('views', join(DIST_FOLDER, 'browser'));
// serve static file from 'dist/browser'
app.get('*.*', express.static(join(DIST_FOLDER, 'browser'), {
maxAge: '30d'
}));
// All regular routes use the Universal engine
app.get('*', (req, res) => {
res.setHeader('Cache-Control', 'max-age=0, private, must-revalidate');
res.render(join(DIST_FOLDER, 'browser', 'index.html'), { req });
});
// Start up the Node server
app.listen(PORT, () => {
console.log(`Node server listening on http://localhost:${PORT}`);
});
应用运行正常,但服务器日志错误: 发送后无法设置headers。 有什么可以帮助我的吗?
我不太了解 ngExpressEngine,但我认为问题在于它会在您发送文件后尝试设置 headers
也许尝试使用 custom callback 这样你就不会发送任何东西我已经为 404 发送了一些东西。
app.get('*', (req, res) => {
res.setHeader('Cache-Control', 'max-age=0, private, must-revalidate');
res.render(join(DIST_FOLDER, 'browser', 'index.html'),
{ req },
(err: Error, html: string) => {
if(res.statusCode != 404 )
res.status(html ? 200 : 500).send(html || err.message);
}
);
});
另一种选择是在您的组件中将状态代码设置为 404,然后如果状态为 404,则从 express 发送文件
(err: Error, html: string) => {
if(res.statusCode != 404 )
res.status(html ? 200 : 500).send(html || err.message);
else res.send('404.html')
}