0

I have the following request in my client code:

$.ajax({
    type: "GET",
    url: "some_external_address.php",
    headers: {
        Authorization: "Bearer " +localStorage.getItem("token") 
    },
    success: function (data) {
        // some code            
    },
    error: function (data) {}
});

And the following server code:

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
header("Access-Control-Allow-Headers: Authorization, X-Requested-With, Content-Type, Accept, Origin");
header('Access-Control-Allow-Credentials: true');

header("HTTP/1.0 404 Not Found");

The problem is that when I send my request without the Authorization header it works well.

But when I need to send an error response with an error code other than 2XX it gives this error: It does not have HTTP ok status.

Victor Yan
  • 181
  • 3
  • 9

3 Answers3

7

I created a headers.php to set default headers for all files with the following code:

<?php
// required headers
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Authorization');
header("Access-Control-Allow-Credentials: true");
header('Content-Type: application/json');
$method = $_SERVER['REQUEST_METHOD'];
if ($method == "OPTIONS") {
    header('Access-Control-Allow-Origin: *');
    header("Access-Control-Allow-Headers: X-API-KEY, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Request-Method,Access-Control-Request-Headers, Authorization");
    header("HTTP/1.1 200 OK");
    die();
}
?>

The problem was that I should handle the OPTIONS method differently, returning a HTTP ok status code.

Source: PHP: How to send HTTP response code?

Victor Yan
  • 181
  • 3
  • 9
1

please try the following code:

$.ajax({
     type: "GET",
     beforeSend: function(request) {
         request.setRequestHeader("Authorization", "Bearer " + your_token_var);
     },
     url: "your_url",
     success: function(resp) {
         console.log(resp);
     }
    });

regards

0

if your error is -(Response to preflight request doesn't pass access control check: It does not have HTTP ok status)

then

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
header("Access-Control-Allow-Headers: Authorization, X-Requested-With, Content-Type, Accept, Origin");
header('Access-Control-Allow-Credentials: true');

header("HTTP/1.0 200 OK");  // <------- update it HTTP/1.0 200 OK