NodeJS 应用程序在本地工作时不响应 GAE 上的任何请求

NodeJS app not answering any request on GAE while working locally

我正在尝试开发 Angular 通用应用程序以部署在 Google App Engine NodeJS 标准环境中。

该应用程序在 运行 node server.js 本地运行良好。

然而,当部署到 GAE 时,页面不断加载并最终失败。在 Google Cloud Console 日志查看器中,我看到这条消息:Process terminated because the request deadline was exceeded. (Error code 123).

package.json 中,启动命令是 "node server.js",而在 app.yaml 中,我仅声明以下内容:runtime: nodejs8.

服务器代码(在TS中,用WebPack打包为JS):

import { enableProdMode } from '@angular/core';
import * as ngUniversal from '@nguniversal/express-engine';
import * as compression from 'compression';
import * as express from 'express';
import * as path from 'path';
import * as detector from 'spider-detector';
import * as appServer from '../dist/server/main.js';
require('zone.js/dist/zone-node');

const ROOT = path.resolve();

enableProdMode();

const app = express();

// Server-side rendering
function angularRouter(req, res): void {
  res.render('index', { req, res });
}

// Enable compression
app.use(compression());

// Check if the user is a bot
app.use(detector.middleware());

// Root route before static files, or it will serve a static index.html, without pre-rendering
app.get('/', angularRouter);

// Serve the static files generated by the CLI (index.html, CSS? JS, assets...)
app.use(express.static('client'));

// Configure Angular Express engine
app.engine('html', ngUniversal.ngExpressEngine({
  bootstrap: appServer.AppServerModuleNgFactory
}));
app.set('view engine', 'html');
app.set('views', path.join(ROOT, 'client'));

app.listen(3000, () => {
  console.log('Listening on http://localhost:3000');
});

在 Google 云控制台日志查看器中,我成功地看到了 "Listening on http://localhost:3000"。

找到解决方案,如果有帮助,我会 post 放在这里。 express 引擎侦听请求(在 GAE 上)的 port 必须用 process.env.PORT

定义

所以,而不是

app.listen(3000, () => {
  console.log('Listening on http://localhost:3000');
});

必须是:

const PORT = process.env.PORT || 3000;

app.listen(PORT, () => {
  console.log(`Listening on http://localhost:${PORT}`);
});