- Forums
- PHP
- Fixed PHP CORS Error: Header Authorization Is Not Allowed According To Header
This Page Contains information about Fixed PHP CORS Error: Header Authorization Is Not Allowed According To Header By edw in category PHP with 0 Replies. [5302], Last Updated: Mon Jun 24, 2024
edw
Sun Mar 31, 2024
0 Comments
751 Visits
To fix the following errors: Add these headers for an API. I was testing this from a React/Vite App with PHP on the backend for API. Multiple Solutions:
source: /f/apachefriends/xampp/htdocs/webune/quiz/api
Solution 1:
header("Access-Control-Allow-Origin: https://localhost:5174");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Allow-Credentials: true");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
header("Content-Type: application/json; charset=UTF-8");
With Multiple ORGINS:
$http_origin = $_SERVER['HTTP_ORIGIN'];
if ($http_origin == "https://localhost:5174" || $http_origin == "https://xxxxx.pages.dev")
{
header("Access-Control-Allow-Origin: $http_origin");
}
Solution 2:
// Decide if the origin in $_SERVER['HTTP_ORIGIN'] is one
// you want to allow, and if so:
header("Access-Control-Allow-Origin: https://localhost:5174");
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, PUT, PATCH, OPTIONS");
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
die('OK!');
}
Source: https://stackoverflow.com/a/76490575
The console errors were:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost/quiz/api/. (Reason: expected ‘true’ in CORS header ‘Access-Control-Allow-Credentials’).
2
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost/quiz/api/. (Reason: CORS request did not succeed). Status code: (null).
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost/quiz/api/. (Reason: CORS request did not succeed). Status code: (null).
Reason: header ‘authorization’ is not allowed according to header ‘Access-Control-Allow-Headers’ from CORS preflight response)
Solution 3
php with axios = error: cors preflight did not succeed
Solution: https://stackoverflow.com/a/55392661