You need to enable JavaScript to run this app. 使用fetch()向PHP接口发送JSON数据时触发JSON解析语法错误的问题排查
优惠活动
大模型
产品
解决方案
定价
更多

使用fetch()向PHP接口发送JSON数据时触发JSON解析语法错误的问题排查

fetch接收响应触发SyntaxError: Unexpected token , in JSON at position 23 排查与解决

现有实现代码

前端请求逻辑

fetch('/api.php', {
    method: 'POST',
    body: JSON.stringify({
        nom: "Issa",
        prenom: "Oule"
    }),
    headers: { "Content-Type": "application/json" },
})
.then(res => res.json())
.then((res) => {
    console.log(res);
})
.catch((err) => {
    console.log(err);
})

后端api.php处理逻辑

<?php
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json');
header('Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token');

$contentType = isset($_SERVER["CONTENT_TYPE"]) ? trim($_SERVER["CONTENT_TYPE"]) : '';

if($contentType === "application/json") {
    $content = trim(file_get_contents("php://input"));
    $decoded = json_decode($content, true);

    if(! is_array($decoded)) {
        echo '{"status":"error decoding"}';
    } else {
        echo '{"status":"ok", "Nom": '. $decoded['nom'];.', "Prenom": '.$decoded['prenom'].'}';
    }
} else {
    echo '{"status":"error data"}';
}
?>

问题根因

  • 后端返回给前端的JSON响应存在语法硬伤,和前端JSON解析要求完全不匹配:
    1. 成功返回分支的字符串拼接链路被多余的PHP语句结束分号打断:原代码在拼接Nom字段值时,在点号连接符后面误写了分号,直接截断了原本的连续字符串拼接流程
    2. 手动拼接JSON时遗漏了字符串值的双引号包裹,不符合JSON语法规范
  • 实际运行时,接口返回的非标准JSON刚好在position 23处出现了语法层面的意外逗号,被res.json()方法解析时直接抛出对应SyntaxError,进入catch分支。
    传参为nom=Issa、prenom=Oule时,拼出来的有效响应片段为{"status":"ok", "Nom": Issa, ...,既没有给文本值加双引号,语法错位后的逗号刚好落在解析器报错的position 23位置。

解决方案

  • 优先弃用手动拼接JSON字符串的写法,改用PHP内置的json_encode()方法序列化返回数据,从机制上保证输出的JSON格式完全合法,规避引号错位、语法断裂类的低级错误。
    修正后的成功分支参考代码:
    if(! is_array($decoded)) {
        echo json_encode(["status" => "error decoding"], JSON_UNESCAPED_UNICODE);
    } else {
        $response = [
            "status" => "ok",
            "Nom" => $decoded['nom'],
            "Prenom" => $decoded['prenom']
        ];
        echo json_encode($response, JSON_UNESCAPED_UNICODE);
    }
    
  • 如坚持手动拼接JSON字符串,需同时满足两个要求:一是拼接链路中不插入会中断流程的PHP分号,二是所有字符串类型的字段值外层包裹符合JSON规范的双引号,修正后的手动拼接参考写法:
    echo '{"status":"ok", "Nom": "'.$decoded['nom'].'", "Prenom": "'.$decoded['prenom'].'"}';
    
  • 补充校验建议:前端在调用res.json()前,可以先打印接口返回的原始文本内容,快速核对后端返回的实际内容,定位格式问题:
    // 替换原直接调用res.json()的逻辑,先做原始内容校验
    .then(async (res) => {
        const rawText = await res.text();
        console.log('接口原始返回内容:', rawText);
        return JSON.parse(rawText);
    })
    

内容的提问来源于stack exchange,提问作者Dra

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.06 02:45:04