【问题标题】:How can I serve my Angular frontend through a Nodejs/Nestjs server deployed on Heroku?如何通过部署在 Heroku 上的 Nodejs/Nestjs 服务器为我的 Angular 前端提供服务?
【发布时间】:2019-11-17 01:51:20
【问题描述】:

我有一个 NestJS api,我想用它来服务前端,来自 Angular。这被部署到heroku上。通过后端路由使用前缀“/api”,我希望所有其他请求都使用我构建的 Angular 应用程序中的 index.html 进行响应。

我部署的应用的文件夹结构是:

-dist
  -client
    -index.html
    -.js files
  -server
    -main.js
    -other dirs/modules

到目前为止,我已经尝试了各种方法,并且它们都在本地工作。问题是部署到heroku。我得到的最接近的(在本文的帮助下:https://medium.com/@bo.vandersteene/use-nest-as-your-server-side-application-with-an-angular-frontend-540b0365bfa3)是在 NestJS 应用程序中创建一个前端中间件,它查看请求路径和文件扩展名,然后使用 res.sendFile 和 path.resolve 创建文件路径回应。

import { Injectable, NestMiddleware } from '@nestjs/common';
import { apiPrefix } from '../../config';
import { Request, Response } from 'express';
import { resolve } from 'path';

const allowedExtentions = [
  '.js',
  '.ico',
  '.css',
  '.png',
  '.jpg',
  '.woff2',
  '.woff',
  '.ttf',
  '.svg',
];

const prefix = apiPrefix;

@Injectable()
export class FrontendMiddleware implements NestMiddleware {
  use(req: Request, res: Response, next: () => void) {
    const { baseUrl } = req;
    if (baseUrl.indexOf(prefix) === 0) {
      next();
    } else if (
      allowedExtentions.filter(extention => baseUrl.indexOf(extention) > 0)
        .length > 0
    ) {
      res.sendFile(resolve(`./dist/client/${baseUrl}`));
    } else {
      res.sendFile(resolve('./dist/client/index.html'));
    }
  }
}

这在本地有效。部署到 heroku 时,我收到一个错误:[ExceptionsHandler] ENOENT: no such file or directory, stat '/app/dist/client/index.html' 不过,这没有意义,因为在我的项目登录 Heroku bash 时,我可以看到确切的文件路径和文件。该文件存在,但由于某种原因,NestJS 无法识别它。

任何帮助将不胜感激。

【问题讨论】:

标签: node.js angular heroku nestjs


【解决方案1】:

我取得了巨大成功的是在您的main.ts 文件中,添加app.useStaticAssets('your/path/to/dist/client'),然后在您的GET / 路径中提供index.html 文件。例如


@Injectable()
export class AppController {
  @Get()
  sendApplication(@Res() res) {
    res.sendFile('index.html');
  }
}

我应该提到,这需要在 Heroku build 阶段或在代码进入 Heroku 之前使用 ng build --prod 构建您的 Angular 应用程序。

【讨论】:

    猜你喜欢
    • 2018-04-18
    • 2019-09-22
    • 1970-01-01
    • 1970-01-01
    • 2020-10-16
    • 1970-01-01
    • 1970-01-01
    • 2021-03-24
    • 1970-01-01
    相关资源
    最近更新 更多