【问题标题】:How to properly set Angular for production in NodeJS Express Server?如何在 NodeJS Express Server 中正确设置 Angular 以进行生产?
【发布时间】:2019-06-15 15:43:20
【问题描述】:

我一直在研究如何在 NodeJS Express 服务器上部署我的 Angular 6 项目,

首先,在开发中,我使用ng serve,它指的是localhost:4200(默认),另一个是localhost:3000 上的Node Express for API(与DB 交互)。在生产中,我也希望从该 Node Express 服务器提供 Angular 构建。

所以我做的是:

  1. 在 Angular 项目的 index.html 上设置 <base href="/">
  2. 运行ng build --prod 100% 顺利,没有错误。
  3. 将Angular上dist/myprojectname中的所有文件复制到views/下的Node Express服务器目录。
  4. index.js 我添加以下行app.use(express.static(path.join(__dirname, '/views/')));

出现类似这样的错误

Refused to apply style from 'http://localhost:3001/styles.a64e6aa0f6090e05d2190.css/' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled.
3localhost/:16 GET http://localhost:3001/runtime.16a329deb1d564eef6599.js/ net::ERR_ABORTED 404 (Not Found)

如果我使用app.use('/*', express.static(path.join(__dirname, '/views/')));

它会给出以下错误: Uncaught SyntaxError: Unexpected token <

【问题讨论】:

    标签: node.js angular express


    【解决方案1】:

    这似乎类似于this issue,您确定您的 css 文件不是以 cmets 开头的吗?

    来自链接问题的答案:

    我认为问题在于以 cmets 开头的 CSS 库。 在开发时,我不会缩小文件,也不会删除 cmets,这 意味着样式表以一些 cmets 开头,导致它是 被视为与 css 不同的东西。

    【讨论】:

    • 不,从 Angular 构建过程生成的 CSS 被缩小并从任何 cmets 中剥离
    • hm...当您构建应用程序时,没有警告或错误?如果您删除所有 CSS 内容会怎样?
    • 问题只是我的构建版本不会从 Node Express 服务器提供服务
    【解决方案2】:

    希望这对您有所帮助,这对我来说非常好。代码的重要部分如下。我的 Angular 应用程序位于 ROOT_FOLDER/dist/index.html 中。您可以在 angular.json 中设置编译/输出路径(变量为 outputPath)。我的 express.js 文件和 package.json 文件就在根文件夹下。

    const bodyParser = require('body-parser');
    const DIST_FOLDER = join(process.cwd(), 'dist');
    const STARTING_SERVER_MSG = 'Running server on port %s';
    const VIEW_ENGINE_STR = 'view engine';
    const HTML_STR = 'html';
    const VIEWS_STR = 'views';
    const BROWSER_STR = 'browser';
      private routes() {
        // This part might be useless STRAT_LINK later
        this.app.set(VIEW_ENGINE_STR, HTML_STR);
        this.app.set(VIEWS_STR, join(DIST_FOLDER));
        this.app.use(express.static(join(DIST_FOLDER)));
        this.app.use(bodyParser.json());
        this.app.use(bodyParser.urlencoded({extended: false}));
        // this.app.use('/env', envRouter);
        // get router
        this.app.use(function (req, res, next) {
          res.sendFile(join(DIST_FOLDER,  'index.html'), {req});
        });
      }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-05
      • 1970-01-01
      • 2013-02-10
      • 1970-01-01
      • 2021-03-13
      • 2023-03-29
      • 2021-11-29
      • 2019-02-28
      相关资源
      最近更新 更多