我正在嘗試使用 fetch 和 catch 方法將 JSON stringfy 請求發送到 PHP 文件,我可以執行某些函數?,F在我沒有收到任何錯誤,但我無法讓該功能正常工作。 fetch('http://localhost/server/mail.php', { method: 'POST', redirect: 'follow', headers : { 'Content-Type': 'application/json', 'Accept': 'application/json' }, body: JSON.stringify({ // Passes values to mail.php name: inputName, phone: inputPhone }), }) .then(response =>{ console.log(response); if(response === 'success'){ history.push("/start"); // Route to another page history.go(0); } }) .catch(function(err) { // Return error console.log(err); });如果我調試,console.log(response)我會收到包含以下內容的反應對象:響應{type:“cors”,url:“http://localhost/server/mail.php”,重定向:false,狀態:200,ok:true,bodyUsed:false,...}最后,我使用 PHP Mailer 庫通過它發送郵件的 PHP 代碼,我之前在另一個項目中使用過相同的代碼,應該可以正常工作。<?phpuse PHPMailer\PHPMailer\PHPMailer;use PHPMailer\PHPMailer\Exception;require './phpmailer/src/Exception.php';require './phpmailer/src/PHPMailer.php';require './phpmailer/src/SMTP.php';$name = $_POST['name'];$from = '[email protected]'$to = '[email protected]'; $message = $_POST['phone'];$subject = '????? ???';$mail = new PHPMailer();$mail->SMTPDebug = 0;$mail->CharSet = 'UTF-8';$mail->SMTPAuth = true;$mail->Host = "server270.web-hosting.com";$mail->Port = 465;$mail->Username = $to;$mail->Password = "*******";$mail->SMTPSecure = "ssl";$mail->setFrom($from);$mail->Subject = $subject;$mail->isHTML(true);$mail->Body = "?? ?????: " . $name . "\r\n <br/> ?????: " . $message;$mail->addAddress($to, 'Yotam Dahan');if(!$mail->Send()){ echo "Error sending: " . $mail->ErrorInfo;}else{ echo "success";}我的問題是 PHP 沒有發送電子郵件,我猜想,inputName并且InputPhone沒有正確傳遞,因此代碼無法運行,響應也不是success應有的樣子。如何通過reactJS中的fetch和catch向PHP發送正確的POST請求?
1 回答

30秒到達戰場
TA貢獻1828條經驗 獲得超6個贊
您正在發送數據,application/json但從$_POST獲取數據application/x-www-form-urlencoded。
您可以使用FormData正確的內容類型創建數據,然后將URLSearchParams其傳遞FormData給獲取函數的主體。
您可以像這樣使用 FormData:
const formData = new FormData();
formData.append("name", inputName);
然后像這樣發送
fetch('http://localhost/server/mail.php', {
method: 'POST',
redirect: 'follow',
body: new URLSearchParams(formData)
});
- 1 回答
- 0 關注
- 152 瀏覽
添加回答
舉報
0/150
提交
取消