PHP与JavaScript中跨域请求被拦截问题排查
跨域POST请求被拦截的解决方法
遇到的错误:
Cross-Origin Request Blocked: 同源策略不允许读取位于"我的Web应用URL"的远程资源。(原因: CORS请求未成功)。状态码: (null)。
我的JavaScript代码:
const url = 'https://opecart9349.000webhostapp.com/unzipper/opencart/index.php?route=customapi/test'; fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json', }, }) .then(response => response.json()) .then(data => { // 处理响应数据 console.log(data); }) .catch(error => { // 处理错误 console.error('Error:', error); });
我的PHP代码:
<?php class ControllerCustomapiTest extends Controller { public function index() { header('Access-Control-Allow-Origin: *'); header('Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE'); header('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With'); header('Content-Type: application/json'); $response = array('success' => true); echo json_encode($response); } } ?>
问题分析与解决步骤
核心问题是浏览器的OPTIONS预检请求未被正确处理。当发送带自定义头的非简单请求时,浏览器会先发送OPTIONS请求确认服务器允许跨域规则,当前代码没有针对OPTIONS请求返回合法响应,导致预检失败。
修改PHP代码,添加OPTIONS请求处理逻辑:
<?php class ControllerCustomapiTest extends Controller { public function index() { // 优先处理OPTIONS预检请求 if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') { header('Access-Control-Allow-Origin: *'); header('Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE'); header('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With'); http_response_code(200); exit(); // 直接终止,无需返回业务数据 } // 处理正常POST/GET请求 header('Access-Control-Allow-Origin: *'); header('Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE'); header('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With'); header('Content-Type: application/json'); $response = array('success' => true); echo json_encode($response); } } ?>
额外检查项
- 确认服务器HTTPS配置正常:如果请求URL是HTTPS协议,服务器必须配置有效SSL证书,否则浏览器会拒绝建立连接,直接导致CORS请求失败。
- 确保PHP代码在输出header之前无任何字符(包括空格、空行),否则头信息无法被正确设置,会引发隐藏错误。
内容的提问来源于stack exchange,提问作者Mohammad Massri
相关产品推荐
相关产品推荐

