使用Fetch实现CRUD时JSON解析报错:'undefined'不是有效JSON
解决Fetch提交FormData时的JSON解析错误
问题描述
开发CRUD系统时,使用Fetch提交表单数据,控制台出现如下错误:
SyntaxError: "undefined" is not valid JSON
at JSON.parse ()
at envio_datos_registro_usuarios.js:19:33
使用Ajax时功能正常,需要修正Fetch的实现。
错误原因分析
- 请求头设置错误:手动指定了
Content-Type: application/json,但实际发送的是FormData对象。Fetch会自动为FormData生成正确的multipart/form-data请求头,手动覆盖会导致后端无法解析表单数据,可能返回非JSON响应。 - Promise链式调用错误:第一个
then中使用逗号运算符(res.json(), console.log(res)),该运算符会返回最后一个表达式的结果(console.log(res)返回undefined),导致第二个then接收的data为undefined,后续JSON.parse(data)自然报错。 - 重复解析JSON:
res.json()已经将响应体解析为JSON对象,无需再调用JSON.parse()。
修正后的代码
JavaScript代码
const d = document; d.addEventListener('DOMContentLoaded', e => { sendDatosForm(); }) function sendDatosForm() { let $btnRegistro = d.getElementById('boton-registrar'); $btnRegistro.addEventListener('click', e => { e.preventDefault(); const datos = new FormData(d.getElementById('formulario-nuevo-usuario')); fetch('./modelo/registrar_usuarios.php', { method: 'POST', body: datos // 移除手动设置的Content-Type,让Fetch自动处理 }) .then(res => { console.log(res); // 单独打印响应信息 return res.ok ? res.json() : Promise.reject(res); }) .then(data => { console.log(data); // 直接使用解析后的JSON对象 }) .catch(err => { console.log(err); }) .finally(() => { console.log('Esto se ejecutará independientemente del resultado de la Promesa Fetch') }) }) }
补充说明
- PHP端代码无需修改,修正后的请求会以正确的FormData格式发送,后端可通过
$_POST['nombre']等方式正常获取表单参数。 - 若要让PHP响应更规范,可添加响应头明确类型:
<?php header('Content-Type: application/json'); $respuesta = array('respuesta' => 'Hello there'); echo json_encode($respuesta); ?>
内容的提问来源于stack exchange,提问作者Kenlymar Paredes
相关产品推荐
相关产品推荐

