Slim Framework with Apache2.4

0

Good morning. I'm creating an API to make a service available to other applications. I have the following scenario. A system to make the service available. This system has a virtualhost configured. The uri is link . When accessing this url, internally using get - the case I have already tested at least - it prints the message on the screen.

$this->app->get("/", function () {
        $header = get_headers('http://www.meuservico.com.br', 1);
        $receive = $header['Content-Type'][0];
        $arr_receive = split(";", $receive);
        echo $arr_receive[0];
    });

I created an external project and it runs on localhost too, but does not have a virtualhost set. Here's the code for external access.

        $(function() {
        $.ajax({
            contentType: "application/json",
            url: 'http://meuservico.com.br/lib/api/api.php',
            data: { name: 'norm' },
            // dataType: "json",
            success: function(data){
                console.log(data);
            },
            error: function (request) {
                console.log(request);
            }
        });        
    });

In this case, I get the following error.

XMLHttpRequest cannot load http://meuservico.com.br/lib/api/api.php?name=norm. Response to preflight request doesn't pass access control check: The 'Access-Control-Allow-Origin' header has a value 'http://www.e-sms.com.br' that is not equal to the supplied origin. Origin 'http://localhost' is therefore not allowed access.
    
asked by anonymous 07.07.2016 / 16:18

1 answer

0

This is not a problem with Apache and Slim, there are missing headers, if you have access to the file http://meuservico.com.br/lib/api/api.php you edit it add the headers, by the error message it already has, but only releases pro http://www.e-sms.com.br then change:

Access-Control-Allow-Origin: http://www.e-sms.com.br

By

Access-Control-Allow-Origin: *

However, if you do not have access to the api.php file, then you can use jQuery itself by applying crossDomain: true, like this:

    $.ajax({
        contentType: "application/json",
        crossDomain: true,
        url: 'http://meuservico.com.br/lib/api/api.php',
        data: { name: 'norm' },
        // dataType: "json",
        success: function(data){
            console.log(data);
        },
        error: function (request) {
            console.log(request);
        }
    });

Note that this is not "real ajax," but works very similar.

    
07.07.2016 / 17:44