发送后无法设置标头。 Angular Universal ExpressJS

时间:2018-04-17 13:17:59

标签: angular express universal

我希望通过服务器端渲染从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}`);
});

应用程序正常,但服务器日志错误: 发送后无法设置标头。 请问有什么帮助吗?

1 个答案:

答案 0 :(得分:1)

我真的不知道ngExpressEngine,但我认为问题是它在您发送文件后尝试设置标题

也许尝试使用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);
  }
  );
});

另一种选择是在组件中将statuc代码设置为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')
  }