0

I am trying to call an API within Angular that requires authorization. My code compiles, but the data does not display, and in the developer tools I get an error message saying that my access has been blocked by CORS policy and there's no access-control-allow-origin. I have been using a CORS Chrome extension to enable CORS. I've provided the code I've been using below, I'm very new to Angular so it's very simple, but I didn't know if there was a way to fix this and get the API call to work? I also do not have access to the server side code, so I cannot add any CORS code on that side.

app.component.ts
import { Component, OnInit } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'My Title';

data: any = {};

constructor(private http: HttpClient) {}

ngOnInit() {

const httpOptions = {
headers: new HttpHeaders({
'Authorization': 'Bearer my-auth-token'
}),
};
this.http.get('https://mygateway.com', httpOptions).subscribe((data)=>{
console.log(data)
});
}

Any help would be appreciated :)

2 Answers2

0

You should implement a proxy file configuration for solve this.

MagnunStalin
  • 94
  • 1
  • 9
0

Best to go through a proxy.. as the #1 answer here suggests: How to add CORS request in header in Angular 5

{
    "/api": {
      "target": "https://mygateway.com",
      "secure": true,
      "changeOrigin": true,
      "pathRewrite": {
        "^/api": ""
      }
    }
  }

then your call would turn into this:

this.http.get('/api', httpOptions).subscribe((data)=>{
console.log(data)
});

Additional info here: https://levelup.gitconnected.com/fixing-cors-errors-with-angular-cli-proxy-e5e0ef143f85

There are other options like using fetch instead also enumerated in the SO link at the top.

Wild Bill
  • 51
  • 1
  • 3