CORS 在PHP 中不起作用
嘗試從www.siteone.com 向www.sitetwo 發送包含表單資料的POST 請求時。使用CORS 存取com 時,遇到以下錯誤:
XMLHttpRequest cannot load http://www.sitetwo.com/cors.php. Origin http://www.siteone.com is not allowed by Access-Control-Allow-Origin.
儘管在www.sitetwo.com 上的cors.php 中配置了CORS 標頭:
<code class="php">header('Access-Control-Allow-Origin: *'); header('Access-Control-Allow-Methods: POST, GET, OPTIONS');</code>
請求仍然失敗,因為頭配置的不正確實作。解決此問題的更新代碼是:
<code class="php">// Allow from any origin if (isset($_SERVER['HTTP_ORIGIN'])) { header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}"); 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, OPTIONS"); if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS'])) header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}"); exit(0); } echo "You have CORS!";</code>
此修訂後的代碼回應 OPTIONS 請求期間收到的存取控制標頭,並允許來自任何來源的請求,從而允許 CORS 正常運作。
以上是儘管設定了 Access-Control-Allow-Origin 標頭,為什麼 CORS 在我的 PHP 應用程式中不起作用?的詳細內容。更多資訊請關注PHP中文網其他相關文章!