【发布时间】:2021-01-17 07:04:57
【问题描述】:
我编写了一个 Asp.Net Core api,到目前为止它运行良好,但是当我尝试发送一个帖子请求时,它给了我Access to XMLHttpRequest at 'https://localhost:44339/api/drawing/checkout' from origin 'http://localhost:4200' 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.
我在后端(startup.cs)上启用了 CORS,如下所示:
services.AddCors(options =>
{
options.AddPolicy(name: MyAllowSpecificOrigins,
builder =>
{
builder.WithOrigins("http://localhost:4200")
.AllowCredentials()
.AllowAnyHeader()
.AllowAnyMethod();
});
});
和app.UseCors(MyAllowSpecificOrigins);
我已经为此浪费了几天时间,我的 GET 请求以及使用 Insomnia 的 POST 请求都有效。有人可以帮我处理 Angular 部分吗?这是我的代码
在 drawing.service.ts 上:
test(param) {
return this.http.post(this.url + '/checkout', param, {
headers: { 'Content-Type': 'application/json' },withCredentials:true
});
}
在我的组件 ts 上:
test() {
let stringfiedArray = JSON.stringify(this.viewerPerm);
console.log(stringfiedArray);
this.drawingSearchService.test(stringfiedArray).subscribe();
}
【问题讨论】:
-
你能分享一个你的 Insomnia 请求的 URL 示例吗?
-
URL:localhost:44339/api/drawing/checkout,使用NTML认证,发送JSON为body,header为Content-Type application/json
-
正如我所怀疑的那样。您需要在 CORS 配置中配置您的 API URL。将
https://localhost:44339添加到您的 CORS 策略来源,然后重试。 -
您可以在配置中添加多个来源。
-
我仍然遇到同样的错误
标签: c# angular api asp.net-core cors