2

I'm trying to pull some data from this api 'https://api.alternative.me/fng/?limit=1&format=csv&date_format=us' from my service class, but I'm getting CORS errors. This is the full error Access to XMLHttpRequest at 'https://api.alternative.me/fng/?limit=1&format=csv&date_format=us' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Here is the service class

const httpOptions = {
  headers: new HttpHeaders({
  'Content-Type':  'application/json',
  'Access-Control-Allow-Origin': '*' ,
  })
};

 @Injectable({
  providedIn: 'root'
 })
 export class CryptoCoinsService {
 constructor(private http: HttpClient) { }

   fng: string = 'https://api.alternative.me/fng/?limit=1&format=csv&date_format=us';

   getFng(): Observable<any[]> {
    return this.http.get<any[]>(this.fng, httpOptions);
   }
  }

And in my component.ts file

 ngOnInit(){
   this.getFng();
 }

getFng() {
  this.cryptoCoinService.getFng()
  .subscribe((data:any) => {
    this.fng = data;
  })
 }

I've tested pulling data this way from coingecko api and it works fine.

service.ts file

 api: string = 'https://api.coingecko.com/api/v3/coins/markets?vs_currency=usd&order=market_cap_desc&per_page=20&page=1&sparkline=false';

getCoinData(): Observable<Coin[]> {
 return this.http.get<Coin[]>(this.api, httpOptions);
}

component.ts file

  ngOnInit(): void {
   this.getTopCoins();
  }

 getTopCoins() {
  this.cryptoCoinService.getCoinData()
   .subscribe(data => {
     this.topCoins = data;
   });
  }

I've read up on CORS errors so I get that the api isn't on the same domain, which is why Im getting the error. I've tried to create a proxy, which im not sure is correct, but I've tried a bunch of combinations for the target and /fng.

{
  "/fng":{
     "target": "https://api.alternative.me",
     "secure": false,
     "logLevel": "debug",
     "changeOrigin": true
 }
}

The error also is saying No 'Access-Control-Allow-Origin' header is present on the requested resource. But my headers contain that option as '*'

Can anyone explain to me what I'm doing wrong and how to fix it? Thanks.

Marrs
  • 21
  • 2
  • Does this answer your question? [Response to preflight request doesn't pass access control check](https://stackoverflow.com/questions/35588699/response-to-preflight-request-doesnt-pass-access-control-check) –  Apr 18 '23 at 01:48
  • I looked through this before I posted this question. It did help me figure out I needed to create a proxy, but I was unsure how to correctly set it up. The answer below solved it! – Marrs Apr 18 '23 at 03:27
  • How do you solved it ? – Diego Venâncio Jun 03 '23 at 19:55

0 Answers0