首页 > 解决方案 > Angular FE 和 fastAPI GCP VM 上的 CORS 错误

问题描述

您好,我在尝试到达远程端点时遇到 CORS 错误。

我的远程服务器是使用 fastAPI 的 Docker 容器。在服务器端,我添加了这个:

app.add_middleware(
    CORSMiddleware,
    allow_origins=['*'],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

在 Angular 中,我使用 HttpInterceptor 指向 URL:

const requestUrl = (environment.backend_sll ? 'https' : "https") +"://" + environment.backend_ip + req.url.split('/api')[1];

const newHeaders = new HttpHeaders({
            'content-type': 'application/json',
            'Access-Control-Allow-Origin': '*',
            "Access-Control-Allow-Headers": "Origin, X-Requested-With, Content-Type, Accept"
        })

        const extendedReq = req.clone({
            url: requestUrl,
            headers: newHeaders,
            body: {...req.body, user_session_id}
        });

return next.handle(extendedReq).pipe(...

运行此设置时,我收到此错误:

在此处输入图像描述

我知道在 Angular 中您可以使用 localhost 的代理,但在生产中不使用此代理文件,而且我的远程端点不在我的主机名所在的位置,所以我得到相同的错误和错误的 IP 地址,因为 Angular 正在使用我的主机名和不是远程IP地址。因此,我在 HttpInterceptor 中覆盖 URL 并输入我想要的 IP 地址。

我如何知道问题出在 FE 还是 BE 上?有没有办法在 FE 和 BE 中完全删除 CORS 规则我知道安全原因。

标签: angularfastapi

解决方案


有一个临时解决方案。

  1. 使用 Chrome/Firefox 扩展,您可以管理 cors 错误。这是一个临时修复,将在开发中工作。

    允许cors访问控制


推荐阅读