angular - 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 规则我知道安全原因。
解决方案
有一个临时解决方案。
使用 Chrome/Firefox 扩展,您可以管理 cors 错误。这是一个临时修复,将在开发中工作。
推荐阅读
- c# - 从 MongoDB 存储和取回文件
- android - 将 dd-mm-yy 字符串转换为 dd-mm-yyyy
- ruby-on-rails - 如何在 Ruby on Rails 上使用 base64 编码传递字段?
- css - 许多 CSS 文本阴影
- python - Python groupby ID 并增加关联列
- html - 一个 Font Awesome Icon 具体已停止在我的 wordpress 网站上显示
- node.js - Mongoose 无法进行深度填充
- c++ - 在 Windows x86 上安装 qt 5.5.1 msvc 2012
- reactjs - 连接组件的酶 wrapper.instance() 为空
- c# - 从不同的表中检索数据