You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP无法接收JavaScript Fetch API的POST请求体问题排查

问题解决:Fetch发送JSON到PHP+Fat-Free框架接收失败

我正在开发一个从网站获取输入并通过PHPMailer发送数据的程序,前端使用JavaScript Fetch API以JSON格式发送POST请求,后端采用PHP+Fat-Free框架。开发中遇到服务器无法接收JSON数据的问题,具体表现如下:

  • 报错500内部服务器错误:提示Content-Type must be application/json;
  • 服务器能检测到请求,但$_POST数组为空,无法查看接收内容;
  • Postman测试时,移除Content-Type检查后邮件可正常发送,但网页表单仍无法发送;
  • 将Content-Type获取方式改为apache_request_headers()后,Postman和网页表单均通过检查,但仅Postman能成功发送邮件,网页表单不行,且两者的$_POST数组均为空。

最终排查发现问题出在textarea的pm值查询方式不正确,现已修复。


JavaScript代码

function prepareSendList(){
    let newsletterRecipients = retrieveCheckedSubscribers();

    newsletterRecipients.forEach(recipient => {
        sendToMailer(createEnvelope(recipient));
    });
}

function createEnvelope(clientID){
    let fname = document.querySelector(`#cr-${clientID} > .fname`).textContent;
    let lname = document.querySelector(`#cr-${clientID} > .lname`).textContent;
    let email = document.querySelector(`#cr-${clientID} > .email`).textContent;
    let pm = document.querySelector(`#pm-${clientID}`).value;

    return {
        fname: fname,
        lname: lname,
        email: email,
        pm: pm
    };
}

function sendToMailer(newsletterEnvelope) {
    let uri = "http://localhost/mailer/send";
    let params = {
        method: "POST",
        body: JSON.stringify(newsletterEnvelope),
        headers: {
            "Content-Type": "application/json"
        }
    };

    fetch(uri, params)
        .then(r => {
            console.log(r);
        });
}

原始PHP后端代码

$f3->route('GET|POST /send', function(){
    $GLOBALS['controller']->send();
});
      
function send(){
        $myfile = fopen("newfile.txt", "w") or die("Unable to open file!");
        fwrite($myfile, var_export($_POST, true));
        fclose($myfile);

        if($_SERVER['REQUEST_METHOD'] != 'POST'){
            throw new Exception("Only POST Requests Permitted");
        }

        $content_type = isset($_POST['CONTENT_TYPE']) ? $_POST['CONTENT_TYPE'] : "";
        if(stripos($content_type, 'application/json') === false){
            throw new Exception("Content-Type must be application/json");
        }

        $body = file_get_contents("php://input");

        $envelope = json_decode($body, true);
        $GLOBALS['newsletterSender'] ->
          sendMail($envelope['email'], $envelope['fname'], $envelope['lname'],
            "ShadowGraph Newsletter", "", $envelope['pm']);
}

更新后的日志收集代码

$myfile = fopen("newfile.txt", "w") or die("Unable to open file!");
fwrite($myfile, 'POST: ' . var_export($_POST, true) . "\n");
fwrite($myfile, 'Apache Req Headers: ' . var_export(apache_request_headers(), true) . "\n");
fclose($myfile);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 04:59:49