No 'Access-Control-Allow-Origin' header using php

Asked

Viewed 11,133 times

2

I am trying to make a simple request via localhost to an external server, but without success. Can anyone help me?

$(function(){
        jQuery.support.cors = true;
        $.ajax({
            type: 'get',
            crossDomain: true,
            url: 'http://meusiteaqui.com',
            success:function(e){
                //window.location=e;
                alert(e)
            }
        })

    });
  • Enter the error message to facilitate help.

2 answers

6


This is because the meusiteaqui.com is not authorizing, there are two solutions:

1. Authorize via Header:

You need to add that:

<?
header("Access-Control-Allow-Origin: *");

//...
?>

On the page in question, to allow the connection of any other site, including the localhost. Some browsers may continue to prevent this for security reasons.

You can also do this in htaccess, for example:

<FilesMatch "\.(php|html|htm)$">
    <IfModule mod_headers>
        Header set Access-Control-Allow-Origin "*"
    </IfModule>
</FilesMatch>

2. Use the JSONP:

Modify your PHP to something similar:

$seusDados = array('id' => 1);
// Exemplo

$seuJSON = json_encode($seusDados);

if(isset($_GET['jsonp'])){
  echo $_GET['jsonp'] . '(' . $seuJSON . ')';
}else{
  echo $seuJSON;
}

You can use something similar to:

<script>

MinhaResposta(MeuJSONP){
   alert(MeuJSONP.id)
}

</script>
<script type="text/javascript" src="http://meusiteaqui.com?jsonp=MinhaResposta"></script>

If you want to know more about JSONP click here.

  • It’s wrong, the correct thing is to release the site address in CORS, because with * you let the api be accessed by any address, completely taking away the security of it.

  • @Ivanferrer, "via localhost to an external server", the localhost could have any domain name, any Host. Obviously you can specify the Host (and it is really recommended to specify), but in this case the Host is undetermined by the OP. In the reply I mentioned that "to allow the connection of any other site", so I think it is clear that this will allow any site to connect, which includes the localhost.

-4

Doing tests on localhost:8000, and using Lumen from Laravel I was able to release using the tip of this post, putting the code in the driver builder.

       /**
         * Create a new controller instance.
         * @return void
         */
        public function __construct()
        {
            header("Access-Control-Allow-Origin: 127.0.0.1");
        }

Browser other questions tagged

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