API Consumption with Fetch js

Asked

Viewed 82 times

-1

This is devs... I’m trying to consume the federal government’s API on emergency relief. My problem is when I fetch, I get returned this error:

inserir a descrição da imagem aqui

codigo:

async function buscar() {
var link =
'http://www.transparencia.gov.br/api-de-dados/auxilio-emergencial-por-cpf-ou-                   
 nis?codigoBeneficiario=0000&pagina=1';
var head = new Headers();
head.append('chave-api-dados', 'codchave');
head.append('Accept', '*/*');
head.append('Access-Control-Allow-Origin', '*');
head.append('Content-Type', 'application/x-www-form-urlencoded');
var req = new Request(link, {
headers: head,
});
let data = await fetch(req);
let da = await data.json();
console.log(da);
}
  • Error of CORS means that you are trying to consume an API from another domain, but this API is not public, and you are not granting your domain permission either. Apparently you tried to add in your header the Access-Control-Allow-Origin, But it’s not your request that needs this header, it’s the server response that needs it, so what you did won’t do you any good. To consume this API you will have to make the request via your server, and not via the front end of the website, because CORS only applies to browsers.

  • I understood more or less, and how I make this request via server

1 answer

0


Well...as there was no one who could guide, I went for the answer. The problem was fetch, fetch is interpreted by the browser, and I was doing it in the back end. the simple solution is to use Axios, so the request is made by the server in the back end thus returning the json with the information I need.

Browser other questions tagged

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