I am trying to make a GET/POST Request to my WordPress REST API using Authorization Headers but in response i am getting
preflight request doesn’t pass access control check: It does not have HTTP ok status.
I am using JWT Authentication for WP-API for Authentication and tried almost every possible option found on the internet but no luck.
Have a look at my current .htaccess configurations
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
RewriteCond %{HTTP:Authorization} ^(.*)
RewriteRule ^(.*) - [E=HTTP_AUTHORIZATION:%1]
SetEnvIf Authorization "(.*)" HTTP_AUTHORIZATION=$1
RewriteCond %{REQUEST_METHOD} OPTIONS
RewriteRule ^(.*)$ $1 [R=200,L]
</IfModule>
<IfModule mod_headers.c>
Header always set X-Content-Type-Options "nosniff"
<IfModule mod_setenvif.c>
SetEnvIf Origin "^(http://localhost:3000)$" CORS=$0
</IfModule>
Header set Access-Control-Allow-Origin %{CORS}e env=CORS
Header set Access-Control-Allow-Credentials "true" env=CORS
Header set Access-Control-Allow-Methods "GET, POST, OPTIONS, HEAD" env=CORS
Header set Access-Control-Allow-Headers "*" env=CORS
Header set Access-Control-Expose-Headers "*" env=CORS
<FilesMatch ".(php|html)$">
</FilesMatch>
</IfModule>
I am getting this error when the request is made from axios
Access to XMLHttpRequest at ‘HIDDEN_SERVER_ADDRESS’ from origin ‘http://localhost:3000‘ has been blocked by CORS policy: Response to preflight request doesn’t pass access control check: It does not have HTTP ok status.
In PostMan the calls are working fine and giving desired results.
2
Answers
Trying every possible solution in .htaccess didn't help in my case. So if anyone else is on the same page here is a solution that worked for me.
put this code in the index.php file and it will work like a charm.
The solution provided by Azaz Khan worked for me. I searched for why it worked and I found this about request with OPTIONS method
So I think before the auth request, a request with OPTIONS method has been fired, but the backend API did not give back a 200 OK response. For me the backend sent back a PHP error, maybe a 404 http error, I did not checked, but with this code I am sure the API gives back 200 OK response because of the exit: