node.js - 如何通过部署在 Heroku 上的 Nodejs/Nestjs 服务器为我的 Angular 前端提供服务?

标签 node.js angular heroku nestjs

我有一个 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 无法识别它。

任何帮助,将不胜感激。

最佳答案

我取得的巨大成功在于您的 main.ts文件,添加 app.useStaticAssets('your/path/to/dist/client')然后在您的 GET /您服务的路线index.html文件。例如


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

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

关于node.js - 如何通过部署在 Heroku 上的 Nodejs/Nestjs 服务器为我的 Angular 前端提供服务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56919818/

相关文章:

angular - 未知选项 : '--target' , 未知选项: '--environment' ;尝试在 prod 中构建 ng 应用程序时

git - 推送到 heroku 进行编译超时

ruby-on-rails - Heroku 登台应用程序是否与评论应用程序共享数据库?

node.js - 部署到 heroku 后,firebase 身份验证无法正常工作。仍然在本地主机 :4200 的开发中工作

javascript - 即使在 hasOwnProperty 检查之后也是 "Cannot read property of undefined"

angular - ngx-图 : Build fails

java - 在 Java Play 应用程序上通过 SendGrid 发送邮件失败

javascript - Node-ACl 抛出未处理的拒绝错误

node.js - 如何构建删除请求的签名,该删除请求在nodejs REST实现中删除azure数据存储中的实体?

javascript - 将 ckeditor5 集成到 Angular 项目时得到 ckeditor-duplicated-modules