Problem with CORS at Angular 5

Asked

Viewed 8,567 times

2

Guys I’m with a test application on Angular 5 and I’m trying to consume the Webservice from the top hat. When performing this attempt the following error appears:

Failed to load https://api.cartolafc.globo.com/mercado/status: The 'Access-Control-Allow-Origin' header has a value 'https://cartolafc.globo.com' that is not Equal to the supplied origin. Origin 'https://localhost:4200' is therefore not allowed access.

I know that for test questions I can simply disable this validation either via plugin or by another option. But in the case of a real application. For example, I will create this application and it will consume the Webservice top hat. How to fix this ?

Service:

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Usuario } from '../model/usuario.model';
import { URL_API } from '../util/constantes';
import { Observable } from '../../../node_modules/rxjs';

const httpOptions = {
  headers: new HttpHeaders({'Content-Type':'application/json'})
};

@Injectable()
export class UsuarioService {

  constructor(private http: HttpClient) { }

  public teste2(){
    return this.http.get('https://api.cartolafc.globo.com/mercado/status', httpOptions);
  }
}

Component:

// O botão no meu HTML chama esse método teste()
      public teste(): void{   
        this.serviceUsuario.teste2()
          .subscribe(
            (response) => {
              console.log("Sucesso");
              console.log(response);
            },
            err => {
              console.log("Erro");
              console.log(err);
            }
          )
      }
  • Apparently only the request for the domain https://cartolafc.globo.com/ In this case its application should be in this domain

1 answer

2

First, we need to understand what CORS is.

Cross-origin Resource sharing or cross-source resource sharing is a browser security specification that aims to secure resources from different backgrounds.

Source.

The responsibility for configuring this mechanism lies with the backend. It should tell which domains the API should bar/release access to.

In that case, we don’t have access to the backend to add the miraculous:

Access-Control-Allow-Origin: *.

And now, how to proceed?

As you mentioned, you can use an extension in Chrome to disable CORS, which will work in a development environment. The problem is when it goes into production, since we have no control over the client’s browser.

An option to circumvent this control is to use a reverse proxy, that should monitor your requests and inject the headers of CORS to each requisition.

There are several ways to mount this proxy, one of them is well described in that article, from which I withdrew my first quote.

A similar service is the Cors-Anywhere, which already provides a ready-to-use URL.

The requisition goes like this:

this.http.get('https://cors-anywhere.herokuapp.com/https://api.cartolafc.globo.com/mercado/status').subscribe(r => {
  console.log(r);
}, err=> {
  console.log(err);
});

which returns the expected object:

inserir a descrição da imagem aqui

Does it work? Yes!

Must be used?

Well, in my opinion, if the API developer denied these accesses, it’s for a reason. It’s up to you to decide whether to use this workaround is really necessary.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.