Request blocked by CORS Policy

1

I'm doing an API with Slim Framework and when I test the answer with Postman everything works fine, however when I put it on the server and tried to make an ajax call to test I got the error below.

  

Failed to load link : Redirect from ' link ' to ' link 'has been blocked by CORS policy: No' Access-Control-Allow-Origin 'header is present on the requested resource. Origin ' link ' is therefore not allowed access.

Here is the method I use to return Json:

public function withCustomJson($meta = null, $data = null)
{
    if (isset($data)) {
        $finalResponse['data'] = $data;
    }

    $finalResponse['meta'] = array(
        'status' => (isset($meta['status']) ? $meta['status'] : null),
        'message' => (isset($meta['message']) ? mb_convert_encoding($meta['message'], "UTF-8", "auto") : null)
    );

    $response = $this->withBody(new Body(fopen('php://temp', 'r+')));
    $response->body->write($json = json_encode($finalResponse));

    // Ensure that the json encoding passed successfully
    if ($json === false) {
        throw new \RuntimeException(json_last_error_msg(), json_last_error());
    }

//Allowing CORS as Slim docs states
    $responseWithJson = $response->withHeader('Content-Type', 'application/json;charset=utf-8')
                ->withHeader('Access-Control-Allow-Origin', '*')
                ->withHeader('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type, Accept, Origin, Authorization')
                ->withHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');

    if (isset($meta['codStatus'])) {
        return $responseWithJson->withStatus($meta['codStatus']);
    }
    return $responseWithJson;
}

And here's my Ajax call:

<script type="text/javascript">
      try {
        $.ajax({
            url: 'https://api.mydomain.net/usuario/autenticar',
            type: 'GET',
            dataType: 'json',
            data: {
              xAuthClienteID:'2',
              xAuthChaveApi: '3851b1ae73ca0ca6e3c24a0256a80ace',
              login: 'admin',
              senha: 'teste'
            },
            ContentType: 'application/json',
            success: function(response){
              console.log(response);
            },
            error: function(err){
                console.log(err);
            }
        });
      }
      catch(err) {
        alert(err);
      }
    </script>

It seems that the problem is that CORS requests are not active on my server, so I took a look at the Slim documentation on how to activate and applied to my method of returning Json, but I still get the error. Where am I going wrong?

    
asked by anonymous 15.09.2017 / 15:45

2 answers

1

Look, I've had some problems like these a few times. usually has two motives:

  • The server is not accepting CORS requests (coming from js)
  • The request is being sent as OPTIONS and not as GET, POST, etc.
  • Check the first option in the service. There is something like Access-Control-Allow-Origin

    Then, in your request try to make the headers explicit so that the service understands.

    See if it works ...

        
    15.09.2017 / 15:59
    -1

    I do not know if it solved, but I use it in the Slim Framework.

    Try this:

    <?php
    
    use \Psr\Http\Message\ServerRequestInterface as Request;
    use \Psr\Http\Message\ResponseInterface as Response;
    
    require '../vendor/autoload.php';
    
    $app = new \Slim\App;
    
    
    //cors 
    $app->options('/{routes:.+}', function ($request, $response, $args) {
        return $response;
    });
    $app->add(function ($req, $res, $next) {
        $response = $next($req, $res);
        return $response
                ->withHeader('Access-Control-Allow-Origin', '*')
                ->withHeader('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type, Accept, Origin, Authorization')
                ->withHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
    });
    
        
    18.08.2018 / 02:29