[SOLUCIONADO]Error en Ajax:"falta la cabecera CORS 'Access-Control-Allow-Origin"

Iniciado por $francisco, Febrero 17, 2016, 05:50:34 PM

Tema anterior - Siguiente tema

0 Miembros y 1 Visitante están viendo este tema.

Muy buenas, tengo este error al realizar una peticion ajax pero no logro poder hacerla y en google siempre me dice lo mismo y no funciona.

Código: php
header("Access-Control-Allow-Origin: *");


mi archivo ajax:

Código: javascript
$(document).ready(function(){
$.ajax({
url:'http://miweb.eshost.com.ar/index.php',
method:'POST',
dataType:'json',
})
.done(function(data){
var text = $(data).find("cite").text();
$("#content").text(text);

})
.fail(function(){alert("fail");})
});


mi archivo php.

Código: html5
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>

</head>
<body>
<?php
header("Access-Control-Allow-Origin: *");
echo "hola";
?>
</body>
</html>


y el error completo

Código: text
Solicitud desde otro origen bloqueada: la política de mismo origen impide leer el recurso remoto en http://services.eshost.com.ar/index.php (razón: falta la cabecera CORS 'Access-Control-Allow-Origin').


Lo unico que se me ocurre que mi hosting no me deje hacer esta tipo de peticiones ¿podria ser?

He estado mirando porque ajax no es mi fuerte y al parecer el código está bien, es posible que el servidor esté bloqueando ese tipo de conexiones, pero me extraña ya que te devuelve un mensaje (con sentido), y no ninguno del tipo "Petición bloqueada por motivos de seguridad etc...".

Puedes probarlo por ejemplo en local o en otro hosting para salir de dudas?

Saludos.



Febrero 18, 2016, 02:17:00 AM #2 Ultima modificación: Febrero 18, 2016, 02:20:11 AM por arthusu
Y si intententas poner un .htaccess en tu hosting?

Código: text
# ----------------------------------------------------------------------
# Allow loading of external fonts
# ----------------------------------------------------------------------
<FilesMatch "\.(ttf|otf|eot|woff)$">
    <IfModule mod_headers.c>
        SetEnvIf Origin "http(s)?://(www\.)?(google.com|staging.google.com|development.google.com|otherdomain.net|dev02.otherdomain.net)$" AccessControlAllowOrigin=$0
        Header add Access-Control-Allow-Origin %{AccessControlAllowOrigin}e env=AccessControlAllowOrigin
    </IfModule>
</FilesMatch>


En este caso el ejemplo solo permite fuentes... obviamente tu cambias eso por las extensiones de tus archivos y la URL en lugar de google las URL's de Origen que quieres permitir...

Usando PHP:

Código: php
// Allow from any origin
if (isset($_SERVER['HTTP_ORIGIN'])) {
    header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
    header('Access-Control-Allow-Credentials: true');
    header('Access-Control-Max-Age: 86400');    // cache for 1 day
}
// Access-Control headers are received during OPTIONS requests
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {

    if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
        header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");         

    if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
        header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");

}



Saludos, espero que te sirva c:
Pentest - Hacking & Security Services

Contact me: You are not allowed to view links. You are not allowed to view links. Register or Login or You are not allowed to view links. Register or Login

Probe de muchas maneras y podria ser que mi hosting lo tenga bloqueado de todas maneras encontré la manera de hacerlo con "jsonp"

You are not allowed to view links. You are not allowed to view links. Register or Login or You are not allowed to view links. Register or Login