問題描述:
嘗試透過CORS 傳輸資料時(跨域表單時(跨域)資源共享)從www.siteone.com 到www.sitetwo.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 中設定了以下標頭:
header('Access-Control-Allow-Origin: *'); header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
解決方案:
問題在於CORS 請求標頭的處理方式。以下cors.php 的更新程式碼提供了對CORS 請求的更全面的回應:
<code class="php"><?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); } // Respond to the request echo "You have CORS!"; ?></code>
此修改後的程式碼允許來自任何來源的跨網域請求,驗證請求方法和標頭,快取CORS響應日,並適當回應OPTIONS 請求。
以上是為什麼我的 CORS 請求失敗並顯示「Access-Control-Allow-Origin 不允許來源」?的詳細內容。更多資訊請關注PHP中文網其他相關文章!