简体   繁体   English

CORS 带有 Asp.net 核心 Webpi 的 Angular 应用程序出错

[英]CORS Error in Angular App With Asp.net Core Webpi

I've been given a task to to build a web client that interacts with the following API:我的任务是构建一个与以下 API 交互的 web 客户端:

https://docs.openaq.org/ https://docs.openaq.org/

It should be able to send different parameters to the API, and display the air quality results for a given city in a friendly manner.它应该能够将不同的参数发送到 API,并以友好的方式显示给定城市的空气质量结果。 I've chosen to build an Angular project in Asp.net core.我选择在 Asp.net 核心中构建一个 Angular 项目。

Code in program.cs program.cs 中的代码

var builder = WebApplication.CreateBuilder(args);
var MyAllowSpecificOrigins = "_myAllowSpecificOrigins";


// Add services to the container.

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddCors(options =>
{

options.AddPolicy(name: MyAllowSpecificOrigins,
  policy =>
  {
    policy.WithOrigins("http://localhost:4200")
          .AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin();                                      
   );
});

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI(options =>
{
    options.SwaggerEndpoint("/swagger/v1/swagger.json", "v1");
});
}

app.UseCors(MyAllowSpecificOrigins);

app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();

app.Run();

app.Component.ts code: app.Component.ts 代码:

import { HttpClient } from '@angular/common/http';
import { error } from '@angular/compiler/src/util';
import { OnInit } from '@angular/core';
import { Component } from '@angular/core';

@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
title = 'OpenAQ Application';
pings: any;
readonly ROOT_URL = "https://docs.openaq.org"

posts:any

constructor(private http: HttpClient) { }


async ngOnInit(): Promise<void> {
await this.http.get(this.ROOT_URL + '/ping').subscribe(response => {
  this.pings = response;
}, error => {
  console.log(error);
 });
 }
}

Error being received after launching my angular project.启动我的 angular 项目后收到错误。

Access to XMLHttpRequest at 'https://docs.openaq.org/ping' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. CORS 策略阻止了从来源“http://localhost:4200”访问“https://docs.openaq.org/ping”中的 XMLHttpRequest:没有“Access-Control-Allow-Origin”header 出现在请求的资源。

Does anyone know why this is occurring?有谁知道为什么会这样?

This is happening because browsers work with same origin policy because of which they block response from servers which are from different origin(domain) than your request origin.发生这种情况是因为浏览器使用同源策略,因此它们会阻止来自与您的请求源不同的源(域)的服务器的响应。

This is usually solved by sending Access-Control-Allow-Origin header from server in response, but in this case I see you are using 3rd party API which I guess you won't have control to modify.这通常通过从服务器发送Access-Control-Allow-Origin header 作为响应来解决,但在这种情况下,我看到你正在使用第 3 方 API,我猜你将无法控制修改。 As you have your own backend you can send this request to your backend which can make this 3rd party request, retrieve the response and send it back to browser.由于您有自己的后端,您可以将此请求发送到您的后端,后端可以发出此第 3 方请求,检索响应并将其发送回浏览器。

Solving CORS error from client is not possible but there are ways like proxy which can be used in development environments.无法解决来自客户端的 CORS 错误,但可以在开发环境中使用代理等方法。 I am not much familiar with Angular but I found this article which can help you: https://www.stackhawk.com/blog/angular-cors-guide-examples-and-how-to-enable-it/我不太熟悉 Angular 但我发现这篇文章可以帮助你: https://www.stackhawk.com/blog/angular-cors-guide-examples-and-how-to-enable-it/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM