Angular Universal不呈现index.html

时间:2017-12-12 15:58:09

标签: angular express angular5 angular-universal

我需要一些帮助。

我想用Angular Universal渲染我的Angular应用程序。我使用ng generate universal my-app(@ angular / cli @ 1.6.0)生成了我的服务器文件,它生成了所有必需的服务器文件(main.server.ts,tsconfig.server.ts,...)。我在我的根目录中创建了一个server.ts文件(代码与cli文档中的相同)和webpack.config.js文件(也是相同的)。构建过程完成没有错误,但是当我尝试在浏览器中打开页面时,我得到错误而没有别的(page)。当我查看网络选项卡时,我看到了network error。但是,如果我尝试打开localhost:4000 / index.html,索引文件将被提供/呈现。

注意server.ts中的console.log("does it get here");,当我检查控制台时它会被注销。但索引不会呈现。

server.ts

// 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(), 'dist');

// Our index.html we'll use as our template
const template = readFileSync(join(DIST_FOLDER, 'browser', '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, 'browser'));

// Server static files from /browser
app.get('*.*', express.static(join(DIST_FOLDER, 'browser')));

// All regular routes use the Universal engine
app.get('*', (req, res) => {
  console.log("does it get here");
  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}`);
});

我还下载了angular-universal-started,但它在那里工作,所以我做错了什么?有没有人遇到同样的错误?我真的很感激一些帮助:D

更新 我发现这是因为ngx-translate软件包。我认为这是因为服务器端呈现不支持http请求,翻译文件应该从文件系统中获取而不是http请求(我认为)。

0 个答案:

没有答案