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
相关产品推荐
相关产品推荐

