简体   繁体   中英

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:

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. I've chosen to build an Angular project in Asp.net core.

Code in 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:

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.

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.

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. 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.

Solving CORS error from client is not possible but there are ways like proxy which can be used in development environments. 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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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