Error while consuming Swagger api from the transparence portal

Asked

Viewed 249 times

0

Using this code to consume the api is giving an error in cross-Omain

inserir a descrição da imagem aqui

$('#seguro').click(function(){
  cpf = $('#cpf').val();
  endapitrans = "http://www.transparencia.gov.br/api-de-dados/seguro-defeso-codigo?codigo="+ cpf +"&pagina=1";

  $.getJSON(endapitrans, function(result){
    $.each(result, function(id, pessoaSeguroDefeso){
      for(var i=0;result.length>i;i++){
        $("#api").append(result[i].id + " - " + result[i].pessoaSeguroDefeso.nome + "<br>");
      }
    });
  });

})

1 answer

1


You need to include the domain demo.syspesca.com.br in the CORS list of the www.transparencia.gov.br if you have access to that government api.

If you do not have this access, you can make a "proxy" in php and do the ajax for this file, where it would get the data from the government api. In practice it’s very simple, see:

<?php
// arquivo consulta.php

// Tratar get aqui
$codigo = $_GET['codigo'];

// faz a requisição
$result = file_get_contents('http://www.transparencia.gov.br/api-de-dados/seguro-defeso-codigo?codigo='. $codigo .'&pagina=1');

echo $result;

The ajax part would be:

jQuery(document).ready(function ($) {
    $('#btnBuscar').on('click', function () {
        $.get('consulta.php', {codigo: $('#cpf').val()}, function (resultado) {
            alert("Resultado obtido\nConsulte o console para mais detalhes");
            console.log(resultado);
        }, 'json');
    });
});

Where $('#btnBuscar') would be the search button selector and $('#cpf') would be the selector of the field where the user type the code to search.

Browser other questions tagged

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