ReactJS连接PHP时Fetch报错:res.json()出现Unexpected end of input
解决React Fetch PHP时出现的
Unexpected end of input错误 我来帮你排查这个问题——你遇到的Unexpected end of input错误其实是几个常见的Fetch+CORS+PHP配置问题叠加导致的,咱们一步步拆解解决:
核心问题分析
mode: 'no-cors'是直接诱因
当你设置mode: 'no-cors'时,浏览器会限制你读取响应内容,返回的是一个「opaque response」(透明响应),根本没法用res.json()解析,这就是报错的直接原因——没有可解析的响应内容。客户端错误设置CORS请求头
你在Fetch的headers里加的Access-Control-Allow-Origin这类头,是服务器端应该返回的响应头,不是客户端请求时要发送的,客户端加这些完全无效,反而可能干扰请求逻辑。请求体格式与PHP解析不匹配
你用JSON.stringify(data)发送了JSON格式的请求体,但没有设置Content-Type: application/json头,而且PHP默认不会自动解析JSON请求体,需要手动处理。
解决方案步骤
第一步:修正React组件的Fetch代码
去掉mode: 'no-cors',修正请求头,确保发送标准的JSON请求:
import React from 'react'; class FormCorreo extends React.Component{ enviar(){ const email = document.getElementById("correo").value; console.log(email); fetch("http://localhost/proyectos/send_mail.php",{ method: 'POST', body: JSON.stringify({ email: email }), // 将数据包装成对象,方便PHP解析 headers:{ "Content-Type": "application/json" // 必须设置此头,告知服务器请求体格式 } }) .then(res => { // 先检查响应状态是否正常,再解析JSON if (!res.ok) throw new Error(`HTTP错误!状态码: ${res.status}`); return res.json(); }) .then(resJson => console.log('成功响应:', resJson)) .catch(error => console.error('错误:', error)); } render(){ return( <span className="form-correo"> <input type="email" name="correo" id="correo" placeholder="email@email.com"/> <button id="correobtn" onClick={() => this.enviar()} >ENVIAR POR CORREO</button> <div id="contenido_php"></div> </span> ); } } export default FormCorreo;
第二步:修改PHP文件send_mail.php
需要设置正确的CORS响应头,解析JSON请求体,并返回JSON格式的响应:
<?php // 开发环境允许所有域名跨域(生产环境需替换为你的React域名) header("Access-Control-Allow-Origin: *"); header("Access-Control-Allow-Methods: POST"); header("Access-Control-Allow-Headers: Content-Type"); header("Content-Type: application/json"); // 告知客户端返回内容为JSON // 解析JSON请求体 $input = json_decode(file_get_contents('php://input'), true); if (!$input || !isset($input['email'])) { echo json_encode(['status' => 'error', 'message' => '无效的邮箱数据']); exit; } $userEmail = $input['email']; // 这里编写你的邮件发送逻辑(示例用原生mail函数,也可以用PHPMailer等库) $mailSent = mail('你的目标邮箱@example.com', '新的邮箱请求', '用户邮箱: ' . $userEmail); // 返回JSON格式的响应结果 if ($mailSent) { echo json_encode(['status' => 'success', 'message' => '邮件发送成功']); } else { echo json_encode(['status' => 'error', 'message' => '邮件发送失败']); } ?>
额外注意事项
- 开发环境跨域:如果你的React项目用
create-react-app启动(默认端口3000),而PHP运行在Apache/Nginx的80端口,上述CORS设置即可解决跨域问题。 - 生产环境优化:生产环境不要用
Access-Control-Allow-Origin: *,应指定你的React应用的具体域名(如https://your-react-app.com)。 - 邮件功能测试:本地开发时可以用MailHog等工具模拟邮件发送,避免因为PHP邮件配置问题导致响应异常。
内容的提问来源于stack exchange,提问作者javier partida molina




