![](/img/trans.png)
[英]Access to XMLHttpRequest from origin 'http://localhost:4200' has been blocked by CORS policy (Angular, WebApi)
[英]Access to XMLHttpRequest at 'URL' from origin 'http://localhost:4200' has been blocked by CORS policy:
我以為我允許訪問所有來源,但我仍然收到此錯誤。
Access to XMLHttpRequest at 'localhost:60248/api/page/1' from origin 'http://localhost:4200' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome -擴展,https。
更新添加建議的代碼更改后,錯誤現在已更改。 現在如下:
CORS 策略已阻止從源“http://localhost:4200”訪問“http://localhost:60248/api/page/1”處的 XMLHttpRequest:重定向不允許用於預檢請求。
在 Startup.cs 我有這個:
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>
{
options.AddPolicy(name: "AllowAll",
builder =>
{
builder.AllowAnyOrigin()
.WithMethods("PUT", "DELETE", "GET");
});
});
在我的 controller 我有這個:
[Route("api/[controller]")]
[ApiController]
public class PageController : ControllerBase
{
...
[EnableCors("AllowAll")]
[HttpGet("{id:int}")]
public async Task<IActionResult> GetPageData(int id)
{
...
這是調用端點的 Angular 服務:
export class PageContentService {
constructor(private http: HttpClient) { }
getContent(id: number): Observable<PageContent> {
let headers = new HttpHeaders();
headers = headers.set('Content-Type', 'application/json');
const httpOptions = {
headers: headers
}
return this.http.get<PageContent>(`http://localhost:60248/api/page/${id}`, httpOptions);
}
}
我以為這會解決它,但顯然不是。
我還需要做什么?
您還需要添加中間件。
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
...
app.UseCors();
...
}
我認為您還需要兩件事:
就像 vivek 所說,在您的Configure
方法中將.UseCors()
添加到您的請求管道中。
將.AllowAnyHeader()
添加到策略構建器中的 CORS-Config 中,我認為Content-Type
-Header 默認情況下是不允許的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.