Error "Access-Control-Allow-Origin header is present on the requested resource" [duplicate]

1

I need to insert an API on my site that provides the weather forecast for a particular city, however, the ajax request always returns the error in the browser console. Follow below:

XMLHttpRequest cannot load http://developers.agenciaideias.com.br/tempo/json/são paulo-SP. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:50745' is therefore not allowed access.

The following is the requisition code:

$(document).ready(function () {
    $.ajax({
        url: 'http://developers.agenciaideias.com.br/tempo/json/são paulo-SP',
        type: 'GET',
        dataType: 'json',
        success: function(dados) {
             alert("Success");
        },
        error: function() {
             alert('Failed!');
        }
    });
});
    
asked by anonymous 07.08.2015 / 23:03

1 answer

3

The error:

  

In the 'Access-Control-Allow-Origin' header is present on the requested resource

It means that the header Access-Control-Allow-Origin is missing which allows a different domain site (or port) to be accessed by others.

If you have control over scripts that run in developers.agenciaideias.com.br , you'll need to add that header.

If you are using C #, do the following:

Response.AppendHeader("Access-Control-Allow-Origin", "*");

This will free all domains. If you want to release to only a specific domain, assuming that the domain that is ajax is something like https://exemplo.com (not https):

Response.AppendHeader("Access-Control-Allow-Origin", "http://foo.example");

Another situation that should be highlighted is the use of unencrypted urls, I recommend that you do the following in ajax:

url: 'http://developers.agenciaideias.com.br/tempo/json/' + encodeURIComponent('são paulo-SP'),
    
07.08.2015 / 23:11