POST请求突发No 'Access-Control-Allow-Origin'头错误,求助解决方案
我在网页空间上有一个PHP文件,开头代码如下:
<?php header('Access-Control-Allow-Origin: *'); header("Access-Control-Allow-Methods: PUT, GET, POST"); header("Content-Type:application/json");
另有部署在不同服务器的React站点,通过以下代码发送GET请求一切正常:
export const queryPHP = (f, d, callback, errorCB=null) => { let data = {...d} let url = urlForQuery + '?f=' + f; for(let key in data) url += "&" + key + "=" + encodeURIComponent(data[key]); console.log(url) fetch(url) .then(response => response.json()) .then(json => { if(json.success) callback(json.data); else { if(errorCB == null) console.log(json.data) else errorCB(json.data); } }) }
但发送POST请求时突然报错:
Access to fetch at 'https://...' from origin 'https://...' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
不清楚哪里出现了变化,求解决办法。
1. 处理OPTIONS预检请求
POST请求如果是带自定义头或JSON数据的复杂请求,浏览器会先发送OPTIONS预检请求,原PHP代码未处理这类请求会导致预检失败。修改PHP开头代码:
<?php // 先处理OPTIONS预检请求 if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') { header('Access-Control-Allow-Origin: *'); header('Access-Control-Allow-Methods: PUT, GET, POST, OPTIONS'); header('Access-Control-Allow-Headers: Content-Type'); exit; // 预检请求无需返回业务数据 } // 正常请求的CORS头 header('Access-Control-Allow-Origin: *'); header("Access-Control-Allow-Methods: PUT, GET, POST"); header("Content-Type:application/json");
2. 修正POST请求的发送逻辑
GET请求是把参数拼在URL里,但POST请求需确保fetch配置正确,指定请求方法、头信息和请求体:
// 示例POST请求实现 export const postToPHP = (f, d, callback, errorCB=null) => { fetch(urlForQuery, { method: 'POST', headers: { 'Content-Type': 'application/json', // 发送JSON数据时使用该头 }, body: JSON.stringify({ f: f, ...d }) // 将参数转为JSON字符串 }) .then(response => response.json()) .then(json => { json.success ? callback(json.data) : (errorCB ? errorCB(json.data) : console.log(json.data)); }) .catch(err => { errorCB ? errorCB(err) : console.error('请求失败:', err); }); }
如果PHP通过$_POST接收表单数据,需将Content-Type改为application/x-www-form-urlencoded,并将数据转为key1=value1&key2=value2格式。
3. 检查服务器全局CORS配置
部分主机商的Apache/Nginx服务器存在全局CORS规则,可能近期更新配置覆盖了PHP里的头:
- Apache:查看网站根目录的
.htaccess文件,若存在Header set Access-Control-Allow-Origin相关配置,调整或删除冲突项。 - Nginx:检查站点配置文件,确认
add_header Access-Control-Allow-Origin指令与PHP代码规则一致。
4. 确保PHP输出头之前无内容
若PHP文件开头有空格、换行或UTF-8 BOM头,会导致header()函数失效(HTTP头必须在任何内容输出前发送):
- 用编辑器将PHP文件转为UTF-8无BOM编码。
- 删除文件开头的所有空白字符。
5. 直接测试PHP接口的响应头
用curl或Postman发送POST请求到PHP接口,查看响应头是否包含Access-Control-Allow-Origin: *:
curl -I -X POST https://你的PHP接口地址
若响应头无该字段,说明PHP代码未执行到header部分,可能是文件路径错误或服务器内部错误(如500),需查看服务器错误日志排查问题。
内容的提问来源于stack exchange,提问作者Ginso

