We have two sites on one server. We created a rest api and the api backend codes are located in Site1.com. On the second site, there is a frontend that sends requests to the APIs of the first site But we encounter error 405 and this error : Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://site1.com/t.php. (Reason: CORS preflight response did not succeed)
.htaccess on Site1.com :
<IfModule mod_headers.c>
Header set Access-Control-Allow-Origin "*"
Header always set Access-Control-Allow-Methods "POST, GET, OPTIONS, DELETE, PUT"
Header always set Access-Control-Allow-Headers "x-requested-with, Content-Type, origin, authorization, accept, client-security-token"
</IfModule>
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_METHOD} OPTIONS
RewriteBase /
RewriteRule ^index.html$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.html [L]
</IfModule>
RewriteCond %{HTTP_HOST} ^www.(.*)$ [NC]
RewriteRule ^(.*)$ http://%1/$1 [R=301,L]
API Code Site1.com/t.php :
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
echo json_encode($_POST, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
Console Browser :
OPTIONS
scheme : http
host : Site1.com
filename : /t.php
Address : ***.8.173.***:80
Status405
Method Not Allowed
VersionHTTP/1.1
Transferred431 B (0 B size)
Access-Control-Allow-Headers : x-requested-with, Content-Type, origin, authorization, accept, client-security-token
Access-Control-Allow-Methods : POST, GET, OPTIONS, DELETE, PUT
Access-Control-Allow-Origin : *
Allow :
Connection
Keep-Alive
Content-Length
230
Content-Type
text/html; charset=iso-8859-1
Date
Mon, 28 Sep 2020 12:19:28 GMT
Keep-Alive
timeout=2, max=99
Server
Apache/2
Accept
*/*
Accept-Encoding
gzip, deflate
Accept-Language
en-US,en;q=0.5
Access-Control-Request-Headers
content-type
Access-Control-Request-Method
POST
Connection
keep-alive
Host
Site2.com
Origin
http://Site2.com
Referer
http://Site2.com/
User-Agent
Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:80.0) Gecko/20100101 Firefox/80.0
Advertisement
Answer
There is 2 sides to this question:
1- front-end : In your front-end js request, you should make sure to send data with form data.
2- back-end : In your back-end code you should directly get the request with $_POST global and not with json_decode(file_get_contents(“php://input”), true).