Request blocked by CORS Policy

Asked

Viewed 2,270 times

1

I’m making an API with Slim Framework and when I test the answer with Postman everything works very well, but when I put it on the server and tried to make an ajax call to test I got the error below.

Failed to load https://api.mydomain.net/usuario/autenticar?xAuthClienteID=2&xAuthChaveApi=3851b1ae73ca0ca6e3c24a0256a80ace&login=admin&senha=teste: Redirect from 'https://api.maydomain.net/usuario/autenticar?xAuthClienteID=2&xAuthChaveApi=3851b1ae73ca0ca6e3c24a0256a80ace&login=admin&senha=teste' to 'https://api.mydomain.net/404.html' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested Resource. Origin 'http://localhost' 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 the 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 keep getting the error. Where am I going wrong?

  • You are local trying to request for external api?

  • Yes, the api is hosted on my server.

2 answers

1

Look, I’ve had some problems like this a few times. usually has two motivations:

  1. The server is not accepting CORS requests (coming from js)
  2. 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 explicit the headers, so that the service understands.

See if it works...

  • 1

    I did this in the method of returning the answer: $responseWithJson. It was the first thing I looked for but it didn’t work.

  • What language has developed the service? I think the problem may be in it... Maybe in web.config, or . htaccess etc

  • PHP with Slim Framework

  • See if this exists in your . htacceess: Header set Access-Control-Allow-Origin *

  • The server is Nginx.

  • Take this example: https://stackoverflow.com/questions/7564832/how-to-bypass-access-control-allow-origin

Show 1 more comment

-1

I do not know if it could solve, but I use in Slim Framework.

Try it like 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');
});

Browser other questions tagged

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