angular - Angular 前端和 webapi .NET core 5.0 之间的跨域请求被阻止
问题描述
我有 .NET core 5.0 webapi,需要从 Angular 应用程序中使用,它们都在同一台机器上运行。
我得到的错误是:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:5000/api/Game/GetPossibleMoves. (Reason: CORS request did not succeed).
我做了什么/尝试了什么
- 阅读并尝试应用 SO 的其他答案
- 在后端 .NET core 5.0 上启用 CORS
- 在前端 Angular 中包含 httpOptions
- 禁用windows防火墙(不是原因)
在我尝试过的 ConfigureServices 中:
/* attempt 1
services.AddCors(options =>
{
options.AddDefaultPolicy(
builder =>
{
//builder.WithOrigins("http://example.com", "http://www.contoso.com");
//This is done this way to facilitate connecting frontend and backend
//but this should be changed to enforce certain origins or methods
builder.AllowAnyOrigin(). ;
});
});
*/
/* attempt 2
services.AddCors(options => options.AddPolicy("ApiCorsPolicy", builder =>
{
builder.WithOrigins("http://localhost:4200").AllowAnyMethod().AllowAnyHeader();
}));
*/
services.AddCors(c =>
{
c.AddPolicy("AllowOrigin", options => options.AllowAnyOrigin());
});
services.AddControllers();
在配置方法中
app.UseRouting();
//app.UseCors("ApiCorsPolicy");
app.UseCors(options => options.AllowAnyOrigin());
在 Angular 中,我尝试在 API 上调用 GET
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class BackendService {
private readonly getMovesURL = 'http://localhost:5000/api/Game/GetPossibleMoves';
private httpOptions: any;
constructor(private http: HttpClient) {
this.httpOptions = {
observe: 'body',
responseType: 'json',
/*
headers: new HttpHeaders({
'Access-Control-Allow-Origin':'*'
})
*/
headers:{'Access-Control-Allow-Origin':'*'}
};
}
getGameMoves(): Observable<any> {
console.log('calling: GetPossibleMoves');
return this.http.get<string[]>(this.getMovesURL, this.httpOptions);
}
}
我也尝试过没有任何标题,无论我尝试哪种组合,包括在 SO 中回答非常相似的问题。总是返回这些错误
跨域请求被阻止:同源策略不允许读取位于 http://localhost:5000/api/Game/GetPossibleMoves 的远程资源。(原因:CORS 请求未成功)。
解决方案
管道的顺序放在app.UseCors();
您的顶部Configure()
。
在有角度的一侧移除headers:{'Access-Control-Allow-Origin':'*'}
以解决:
跨域请求被阻止:同源策略不允许读取位于 http://localhost:5000/api/Game/GetPossibleMoves 的远程资源。(原因:根据 CORS 预检响应中的标头“Access-Control-Allow-Headers”,标头“access-control-allow-origin”是不允许的)。
推荐阅读
- excel - 计算具有子字符串的合并单元格
- audio - 音频比特率变化对频谱图的影响
- android - 好像有错误,没有
- r - 尝试在 R 中使用单独()函数时在 UseMethod 中出现错误
- javascript - 即使使用空括号,如何修复 React 的 useEffect 无限循环?
- javascript - JavaScript 以编程方式检查是否正在使用相机
- html - 如何获取图像高度并将该高度赋予图像 div 以使其响应
- mysql - MYSQL - 无法添加外键约束,但为什么呢?
- asp.net-mvc - Razor 默认使用 SignalR 吗?
- azure - Azure 逻辑应用 - 如何跨多个资源组共享集成帐户