Error "Access-Control-Allow-Origin header is present on the requested Resource"

Asked

Viewed 1,018 times

1

I need to insert an API on my site that brings the weather forecast for a certain city, however, the request ajax always returns the error in the browser console. 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.

Follow 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!');
        }
    });
});

1 answer

3


The mistake:

No 'Access-Control-Allow-Origin' header is present on the requested Resource

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

  • Read more about CORS

If you have control over the scripts that run on developers.agenciaideias.com.br, it will be necessary to add such a header.

If you’re using c#, do the following:

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

This will release to all domains. If you want to release to just one specific domain, assuming that the domain that is ajax is something like https://exemplo.com (and don’t be https):

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

Another situation worth mentioning is the use of uncoded urls, I recommend doing the following in ajax:

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

Browser other questions tagged

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