0

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.

9
  • 2
    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 Commented Jul 24, 2018 at 17:24
  • I do not understand this very well, I just went on Network Headers and there it is Request Method: OPTIONS, Status Code: 200 OK Commented Jul 24, 2018 at 17:27
  • 1
    That's a good start. There is also a response body tab normally. Nothing there for the OPTIONS request? Commented Jul 24, 2018 at 17:28
  • in my response headers it says that the status is 200 but I can not find anything referring to options Commented Jul 24, 2018 at 17:30
  • 1
    Yes if you could do that. Showing request and response headers Commented Jul 24, 2018 at 17:51

1 Answer 1

4

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);
}
Sign up to request clarification or add additional context in comments.

1 Comment

I was able to load the data into netword but it was not yet for the application

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.