0
votes

I'm creating an angular application 6 and api rest in php. when my angular application tries to perform a request the following url: http://localhost/bdevApi/api/index/categoryexame?page=1 the following error is loaded:

Failed to load Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access.

The angle is in port 4200 and my api is in 80

I visualized some tutorial and added the following header to my api

api/index.php

  <?php
    header('Access-Control-Allow-Origin: *');
    header('Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS');
    header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token');

    include("config/config.php");
    include("import/Interpreter.php");
    include("import/SendJson.php");
    include("database/Connection.php");
    include("import/AuthToken.php");

    $db = Connection::getInstance();

    if( $db->getStateConnection() )
    {
        $arrayHeader = getallheaders();
        $token = isset($arrayHeader["token"]) ? $arrayHeader["token"] : ""; 

        // Recupera dados via Json
        $strJson = file_get_contents('php://input'); //echo $strJson;
        $jsonObject = json_decode($strJson); //var_dump($strJson);


        $Interpreter = new Interpreter(
            "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]", 
            $_SERVER['REQUEST_METHOD'],
            $jsonObject
        );

        if(AuthToken::validateToken($token))
            $Interpreter->initializes(true);
        else
        {
            if($token == "") 
                $Interpreter->initializes(false);       
            else
            {
                $S = new SendJson();
                $S->Send("200", "1", "Token não autenticado", null);
            }   
        }
        $db->closeConnection();
    }

    ?>

How do I get my application to accept these headers and not show this error?

[EDIT] [enter image description here]1

new error

Failed to load http://localhost/bdevApi/api/index/categoriaexame?page=1: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access.

1
Did u check in chrome debugger the response body and headers for the OPTIONS request? If it's Options your server should return 200 straight away. Maybe it's going through the rest of the code and returning something else - David
I do not understand this very well, I just went on Network Headers and there it is Request Method: OPTIONS, Status Code: 200 OK - Emiry Mirella
That's a good start. There is also a response body tab normally. Nothing there for the OPTIONS request? - David
in my response headers it says that the status is 200 but I can not find anything referring to options - Emiry Mirella
Yes if you could do that. Showing request and response headers - David

1 Answers

4
votes

This is happening because of cross origin policy. You can go through this document to get the details knowledge about CORS:

https://developer.mozilla.org/en-US/docs/Web/HTTP/Server-Side_Access_Control

You can try this code below:

// 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, OPTIONS");         

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

    exit(0);
}