问题描述:
尝试通过 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中文网其他相关文章!