0

i have trouble with cross origin access. When i send a request without a bearer token in Authorization header, it's work. When i do the same request with a bearer token, i have the following alert :

Access to XMLHttpRequest at 'XXX/API/TEST/TEST.php' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.

In my php API i have the Following header :

header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: *");
header("Access-Control-Max-Age: 3600");
header ("Access-Control-Allow-Headers: Content-Type, Authorization, Accept, Accept-Language,X-Authorization");

In my js script i have that :

xhr.setRequestHeader("Accept", "application/json");   
xhr.setRequestHeader("Authorization", "Bearer " + getCookie(COOKIE_NAME));
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');

I have seen the folowing advice :

On the client, specify the Authorization header you want to include in the request.

On the server, respond with Access-Control-Allow-Origin header, containing the origin that performs the request, or a wildcard.

On the server, respond with Access-Control-Allow-Headers: Authorization to inform the browser that the Authorization header in the request is permitted.

But i can't get it work.

EDIT 1 I have found what was wrong : When i use method PUT or DELETE it send a preflight request with "OPTIONS" as method type. But my php code didn't allow OPTIONS, i add the following code after my headers and it's work fine !

if($_SERVER['REQUEST_METHOD'] === "OPTIONS"){
    http_response_code(200);
    exit;
}
Charley
  • 9
  • 3

0 Answers0