我可以在同一个 FastApi 中提供一个 angular 应用程序吗?当然,它有 Api?

Can I serve an angular application in the same FastApi which have, of course, the Api?

我有一个用 FastApi 框架开发的 Api。 我有一个 Angular 调用 FastApi 的应用程序。 由于多种原因,如果我能将 FastApi 中的 angular 应用程序部署为一个简单的 Web 应用程序,那就太好了(网络名称、参数、docker 图像等)。这样我就可以将 Api 作为“本地主机”访问,而 Api 可以是“私有的”。

这可能吗?

谢谢, 何塞·克鲁兹

不,据我所知这是不可能的。这就像说两种不同的语言。使用 JSON 个文件,您可以共享配置,但不能共享更多。

也许在低级别上(python 和 nodejs 都是用 C 或 C++ 编写的),你可以绑定它们,但是这样做比简单地产生两个开销要多得多单独的容器。

此外,将 API 和前端分开是一个很好的做法,它允许您以更简单的形式执行 changes/updates 并在突然高峰的情况下扩展一项服务。此外,安全性得到提高,因为两个容器实际上是分开的并且由容器固定。闯入一个,不一定会危及第二个(我说会,因为这取决于您存储的访问信息以及您授予前者的权限)。

我不知道它是否可以帮助你,但它对我有用。

我警告你这不是一个好的做法,但在我应用它的上下文中解决了我的问题。

我有一个小型 Angular 应用程序,可以登录并验证重定向到 FastAPI 的 Redoc 和 Swagger 文档。

我设置了一个包含静态文件的目录,并将 angular 构建放在里面。在 FastAPI 中,我创建了一个端点读取和服务 index.html 文件。

为了 angular 查看文件,我通过传递 --base-href 标志来构建 Angular 指向挂载的静态目录。

代码如下所示:

project/
    static/
        index.html
        ... (files app angular)

    main.py

main.py

from fastapi import FastAPI
from fastapi.responses import HTMLResponse
from fastapi.staticfiles import StaticFiles


app = FastAPI()

app.mount("/static", StaticFiles(directory="static"), name="static")


@app.get('/')
def get_app_angular():

    with open('static/index.html', 'r') as file_index:
        html_content = file_index.read()
    return HTMLResponse(html_content, status_code=200)

构建APPAngular:

ng build --base-href static/ --prod