我可以在同一个具有 Api 的 FastApi 中提供角度应用程序吗?

jos*_*ruz 1 angular fastapi

我有一个在 FastApi 框架中开发的 Api。\n我有一个调用 FastApi 的 Angular 应用程序。\n由于多种原因,如果我可以在FastApi 作为一个简单的 Web 应用程序。这样我就可以作为“localhost”访问 Api,并且 Api 可以是“私有”的。

\n

这可能吗?

\n

谢谢你,\n乔斯\xc3\xa9 克鲁兹

\n

Pat*_*cia 7

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

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

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

我设置了一个包含静态文件的目录并将角度构建放入其中。在 FastAPI 中,我创建了一个端点来读取并提供 index.html 文件。

为了让 Angular 能够查看文件,我通过传递指向已安装静态目录的--base-href标志来构建 Angular。

代码如下所示:

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

    main.py
Run Code Online (Sandbox Code Playgroud)

主要.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)
Run Code Online (Sandbox Code Playgroud)

构建 APP 角度:

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