Does anyone know why i might be getting the following CORS error?

Aaron.soggi92

Member
Joined
Oct 22, 2021
Messages
18
Programming Experience
Beginner
I have the following task to do:

"The goal of this exercise is to build a web client that interacts with this API. 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.

The client only needs to support the retrieval of data for a city, however there are other parameters and functionality available to the API, such as sorting, which may be useful. Potential features the client could be extended to include for example, storing of requests and replaying them"

API : OpenAQ - Swagger UI

I've set up an angular client project in a ASP.NET Core Web API.

Setting up CORS in Program.CS:

C#:
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();
                                          
                     });

});

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();


Http client request in app.component.ts:

C#:
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;

  constructor(private http: HttpClient) { }

  async ngOnInit(): Promise<void> {
    await this.http.get("https://u50g7n0cbj.execute-api.us-east-1.amazonaws.com/ping").subscribe(response => {
      this.pings = response;
    }, error => {
      console.log(error);
    });
    }
}

LaunchSettings.json:


C#:
{
  "$schema": "https://json.schemastore.org/launchsettings.json",
  "iisSettings": {
    "windowsAuthentication": false,
    "anonymousAuthentication": true,
    "iisExpress": {
      "applicationUrl": "http://localhost:50734",
      "sslPort": 44353
    }
  },
  "profiles": {
    "API": {
      "commandName": "Project",
      "dotnetRunMessages": true,
      "launchBrowser": true,
      "launchUrl": "swagger",
      "applicationUrl": "https://localhost:7138;http://localhost:5005",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    },
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "launchUrl": "swagger",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    }
  }
}

ERROR when launching Angular project:

Access to XMLHttpRequest at 'https://u50g7n0cbj.execute-api.us-east-1.amazonaws.com/ping' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.




I'm a little confused with this task as I've worked on .NET projects before but never had to fetch data from an API documentation.... I've always made the endpoints myself within controllers.

Can someone please give me some advice on how i can get this running? I would really appreciate it - i just need a bit of clarification that's all.
 
Last edited:

Skydiver

Staff member
Joined
Apr 6, 2019
Messages
5,251
Location
Chesapeake, VA
Programming Experience
10+
It is not a matter of seeing up CORS on your client. It is a matter of setting up CORS on the server. The server has to allows calls from other domains while using a browser.

Instead of doing the REST call from the JavaScript that underlies the Angular code running in the browser, call using C# running on your server.
 
Top Bottom