'Preflight CORS error followed by 404 error

I am experiencing an issue when trying to get data from API for my react app. I am trying to pass protect my API using htaccess file so when trying to send auth in Axios get request I receive a CORS error and 404 error.

This is my axios GET request:

getData = async () => {
    const username = "xyxyx";
    const pass = "xyxy";
    const basicAuth = "Basic " + Buffer.from(username +":"+pass).toString('base64');
    console.log("BasicAuth::", basicAuth);
    try {
    const {data} = await axios.get(UrlApi.Url, {
      //  mode: "no-cors" ,
      // headers : { 
        // 'Authorization':  basicAuth,
      // } 
      //  mode: "no-cors", 
      // allowCredentials: true,
      auth:  {
          username: "xyxyx",
          password: "xyxy"
        }
    });

As you can see I have several lines commented as I tried in so many ways to make it work but without success.

Below is the index.php of my API (which I didn't write)

<?php
require "./database.php";
require "./datas.php";

header("Access-Control-Allow-Origin: http://southparagliding.ro");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: OPTIONS,GET,POST,PUT,DELETE");
header("Access-Control-Max-Age: 3600");
// header("Access-Control-Allow-Credentials: true");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, X-Requested-With");


$parsedUrl =  $_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['SERVER_NAME'].':'.$_SERVER['SERVER_PORT'].'/';
$uri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);

$uri = explode( '/', $uri );

// endpoints starting with `/data` for GET, POST, DELETE posts
// everything else results in a 404 Not Found
if ($uri[1] !== 'data') {
  if($uri[1] !== 'datas'){
    header("HTTP/1.1 404 Not Found");
    exit();
  }
  print_r($uri[1]);
}

// endpoints starting with `/datas` for GET by type results in a 404 Not Found
// the post id is, of course, optional and must be a number; same with type
$dataId = null;
$type = null;

if ($uri[1] == 'datas' and isset($uri[2])) {
    $type = (string) $uri[2];
}

if ($uri[1] == 'data' and isset($uri[2])) {
    $dataId = (int) $uri[2];
}

$requestMethod = $_SERVER["REQUEST_METHOD"];

$dbConnection = (new Database())->connect();
// pass the request method and post ID to the Post and process the HTTP request:
$controller = new Data($dbConnection, $requestMethod, $dataId, $type, $parsedUrl);
$controller->processRequest();

Also, see my htaccess file that is inside the de API main folder.

#rewrite works: sp.ro/index.php/data => sp.ro/data 

RewriteEngine on
RewriteCond %{QUERY_STRING} ^$
# RewriteRule ^data$ /index.php/data [L,NE]
RewriteRule ^(.*)$ /index.php/data [L,NE]

RewriteEngine On


<IfModule mod_headers.c>
    Header set Access-Control-Allow-Origin http://localhost:3000
    # southparagliding.ro
    Header set Access-Control-Allow-Credentials true
    Header set Access-Control-Allow-Methods OPTIONS GET POST PUT DELETE
    </IfModule>

# RewriteEngine On
# RewriteCond %{REQUEST_METHOD} OPTIONS
# RewriteRule ^(.*)$ $1 [R=200,L]


#######this somehow works: basic auth for all methods but OPTIONS
# <If "%{REQUEST_METHOD} !=  'OPTIONS'">
# # Authentication directives...
# AuthUserFile "/home3/r94573sout/api/.htpasswd"
# AuthName "LockedApiII"
# AuthType Basic
# Require valid-user
# </If> 

I don't understand where I am going wrong. I have spent a lot of time on this so if you have any idea I will much appreciate it.

Thank you!



Solution 1:[1]

The API which you call does not consider Authorization a CORS-allowed header:

Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, X-Requested-With

Therefore you cannot make requests from a different origin that include authorization like

auth: {
  username: "xyxyx",
  password: "xyxy"
}

because this leads to an Authorization header. This restriction can only be lifted by the one who wrote the API. It must be:

Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, X-Requested-With, Authorization

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Heiko Theißen