从节点服务器提供角度构建输出时出错

时间:2018-05-17 08:48:41

标签: javascript node.js angular

我在名为angular-app的文件夹中创建了一个角度应用,并使用ng build成功创建了一个版本。我使用http-server测试了构建。我导航到angular-app文件夹并运行 http-server ./dist 角度应用程序呈现。这是构建的angular-app/dist/index.html页面。

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>AngularApp</title>
  <base href="/angular-app/">

  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
<body>
  <app-root></app-root>
<script type="text/javascript" src="runtime.js"></script><script type="text/javascript" src="polyfills.js"></script><script type="text/javascript" src="styles.js"></script><script type="text/javascript" src="vendor.js"></script><script type="text/javascript" src="main.js"></script></body>
</html>

现在在angular-app文件夹中,我创建了一个server.js文件,用于从Node端点呈现Angular构建。以下是angular-app/server.js文件的外观:

const express = require('express');
const path = require('path');
const http = require('http');

const app = express();

// Point static path to dist
app.use(express.static(path.join(__dirname, '/dist')));

// Catch all other routes and return the index file
app.get('/angular', (req, res) => {
  console.log(__dirname);
  res.sendFile(path.join(__dirname, 'dist/index.html'));
});

/**
 * Get port from environment and store in Express.
 */
const port = process.env.PORT || '3000';
app.set('port', port);

/**
 * Create HTTP server.
 */
const server = http.createServer(app);

/**
 * Listen on provided port, on all network interfaces.
 */
server.listen(port, () => console.log(`API running on localhost:${port}`));

现在,在运行节点服务器时,我希望Node服务器在加载http://localhost:3000//angular时呈现Angular应用程序。 但是我在浏览器控制台中给出了以下错误。

GET http://localhost:3000/angular/angular-app/runtime.js 404 (Not Found)
Refused to execute script from '<URL>' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled.
angular:13 GET http://localhost:3000/angular/angular-app/polyfills.js 404 (Not Found)
favicon.ico:1 GET http://localhost:3000/angular/angular-app/favicon.ico 404 (Not Found)

关于我错过的任何想法?

更新:根据评论将app.get('/ angular')更改为app.get('*'),但在控制台中仍然出现以下错误。

Uncaught SyntaxError: Unexpected token <
polyfills.js:1 Uncaught SyntaxError: Unexpected token <
styles.js:1 Uncaught SyntaxError: Unexpected token <
vendor.js:1 Uncaught SyntaxError: Unexpected token <
main.js:1 Uncaught SyntaxError: Unexpected token <

1 个答案:

答案 0 :(得分:1)

您的服务器不提供http://localhost:3000/angular/angular-app/polyfills.js等文件 - 您需要对dist/的所有文件请求进行重定向 - 目前只有一个 - /angular/dist/index.html

在这里,您可以获得有关如何操作的更多信息:https://blog.cloudboost.io/run-your-angular-app-on-nodejs-c89f1e99ddd3