【发布时间】:2021-09-18 14:04:45
【问题描述】:
我正在尝试向URL = "https://sambhav.daily.co/v1/rooms" 发出发布请求,但我收到了被 cors 政策阻止的错误
addRoom(): Observable<any> {
const headers = new HttpHeaders()
.set("content-type", "application/json")
.set("Access-Control-Allow-Origin", "http://localhost:8000")
.set("Access-Control-Allow-Methods", "GET,POST,PATCH,DELETE,PUT,OPTIONS")
.set(
"Access-Control-Allow-Headers",
"Origin, Content-Type, X-Auth-Token, content-type"
)
.set(
"Authorization",
`Bearer <API-KEY>`
);
return this.http
.post(URL, { headers: headers })
.map((response: any) => response.data)
.catch(this.handleError);
}
我收到的错误
Access to XMLHttpRequest at 'https://sambhav.daily.co/v1/rooms' from origin 'http://localhost:8000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
【问题讨论】:
-
更新您的 服务器 上的代码以允许来自 localhost:8000 的请求。代码中的那些
access-control-*标头无关紧要,因为它们在客户端上。需要返回这些标头的是服务器。 -
@RoddyoftheFrozenPeas 我每天都在使用第三方服务并向它发出帖子请求
-
我不确定,但我猜您正在开发并想针对该服务器进行开发?你需要做的是使用 proxy.conf.json 启动 Angular cli 服务器,检查这个 - angular.io/guide/build#proxying-to-a-backend-server
-
请注意,如果您确实使用代理配置来解决浏览器中的同源限制,您需要确保您的生产应用程序仍然按预期工作。代理仅在 webpack 开发服务器中提供,您不应该在生产环境中运行。
-
不要在请求中设置
Access-Control-*标头。它们是响应标头!