React调用Auth API触发CORS预检错误,求解决方案(附配置代码)
解决CORS预检请求错误:Response to preflight request doesn't pass access control check
这个错误的核心是浏览器发送的OPTIONS预检请求没有得到200 OK响应,下面是针对性的修复步骤:
1. 修改Apache虚拟主机配置,专门处理OPTIONS请求
当前的Header配置不会自动处理OPTIONS请求的状态码,需要添加规则确保OPTIONS请求返回200,并正确设置CORS头:
<VirtualHost *:80> ServerName salesforce-api.local DocumentRoot "C:/xampp/htdocs/projects/project1/htdocs/api/public/" # 强制OPTIONS请求返回200状态码 RewriteEngine On RewriteCond %{REQUEST_METHOD} OPTIONS RewriteRule ^(.*)$ $1 [R=200,L] # 确保所有响应(包括OPTIONS)都带上CORS头,用always保证优先级 Header always set Access-Control-Allow-Origin "http://localhost:3000" Header always set Access-Control-Allow-Methods "GET, POST, PUT, DELETE, OPTIONS" Header always set Access-Control-Allow-Headers "Origin, X-Requested-With, Content-Type, Accept" Header always set Access-Control-Allow-Credentials "true" # 清除OPTIONS请求的多余响应头,避免干扰 Header unset Content-Type Header unset Content-Length SetEnv APPLICATION_ENV "development" <Directory "C:/xampp/htdocs/projects/project1/htdocs/api/public/"> DirectoryIndex index.php AllowOverride All Order allow,deny Allow from all </Directory> </VirtualHost>
修改后重启Apache生效。
2. 后端PHP代码处理OPTIONS请求
如果你的API入口是index.php,需要在代码最开头添加逻辑,直接响应OPTIONS请求,避免执行后续业务代码导致非200状态:
<?php // 处理OPTIONS预检请求,直接返回200 if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') { http_response_code(200); exit(); } // 后续的API业务逻辑... ?>
3. 优化Axios请求配置
前端不需要设置Access-Control-Allow-*这类响应头(这些是服务器返回的,前端设置无效),另外因为你开启了Access-Control-Allow-Credentials: true,需要给Axios加上withCredentials: true:
const headers = { 'Content-Type': 'application/json', 'Accept': '*/*' }; axios.post(apiUrl, requestData, { headers, withCredentials: true // 对应服务器的Allow-Credentials设置 }) .then(response => { setData(response.data); }) .catch(error => { console.error('Error fetching data:', error); });
修复逻辑说明
浏览器在发送跨域POST/PUT等非简单请求前,会自动发送OPTIONS预检请求,验证服务器是否允许该跨域操作。只有当OPTIONS请求返回200 OK,并且头信息符合要求时,浏览器才会发送实际的业务请求。之前的配置没有专门处理OPTIONS请求的状态码,加上后端可能未拦截OPTIONS请求,导致预检失败。
内容的提问来源于stack exchange,提问作者Meesaq Hussain
相关产品推荐
相关产品推荐

