angularJS $ http.get (localhost / test) does not work in Chrome

2

In my controller I have a $http.get(http://www.testesitelocal.com:18888/teste_json) which returns me the values of the test JSON. I make this request on my local machine. In Webview I did in JavaFX this works normal, but in Chrome it does not work (in Firefox and IE normal request occurs).

Error return:

  

XMLHttpRequest can not load http://www.testesitelocal.com:18888/teste_json . In 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://www.testesitelocal.com:8000 <http://www.testesitelocal.com/>' is therefore not allowed access.

    
asked by anonymous 25.02.2014 / 13:26

1 answer

2

I was able to find the answer! Look:

Explicit domain definition: ( 1 , 2 , 3 and 4 )

JavaScript configuration:

With jQuery / Zepto:

function verificaCodigoTurma(codigo, retorno) {
  try {
    $.support.cors = true;
    $.ajax({
      cache: false,
      timeout: 5000,
      //async: false,
      type: 'POST',
      //crossDomain: true,
      url: 'http://TESTESTE/VERIFICA',
      dataType: 'json',
      contentType: 'application/json; charset=utf-8',
      data: '{"sch_code":"' + codigo + '", "app_id":1}',
      //JSON.stringify(teste),
      success: function (data) {
        retorno(data);
      }
    });
  }
  //Exceção geral da sincronização
  catch (err) {}
}

No jQuery / Vanilla-JS:

function verificaCodigoTurma2(codigo, retorno) {
  var xmlhttp = new XMLHttpRequest();

  var params = '{"sch_code":"' + codigo + '", "app_id":1}';

  xmlhttp.open("POST", "http://www.ETESTEr.com.br/Services/TESTE.svc/TESTE", false);
  xmlhttp.setRequestHeader("Content-type", "application/json");
  xmlhttp.setRequestHeader("Content-length", params.length);
  xmlhttp.setRequestHeader("Connection", "close");
  //Para funcionar, além da configuração abaixo é necessário colocar o seguinte header no servidor:
  //Access-Control-Allow-Credentials: true
  xmlhttp.withCredentials = true;
  xmlhttp.send(params);
  var jsonResponse = JSON.parse(xmlhttp.responseText);
  retorno(jsonResponse);
}

You can still use JSONP in the case of GET requests.

For CORS to work you should also configure the server:

IIS:

<system.webServer>
  <modules runAllManagedModulesForAllRequests="true"/>
  <httpProtocol>
  <customHeaders>
    <add name="Access-Control-Allow-Origin" value="*" />
    <add name="Access-Control-Allow-Methods" value="GET, POST" />
    <add name="Access-Control-Allow-Headers" value="Content-Type" />
  </customHeaders>
</httpProtocol>

Apache:

Header add Access-Control-Allow-Origin "*"

Remembering that these settings above allow any website to access your data, removing its security. So try to narrow down the domains covered by Access-Control-Allow-Origin .

Credit: Airton Barbosa who got and went after the correct answer and even offered more than one solution     

25.02.2014 / 14:00