dpwgzi7987 2019-05-15 19:23
浏览 121

使用React-Axios通过PHP传递mgs / mail

I am redoing my current portfolio from html to React based. So my contact form is backed by PHP, of which I am using mail function to send email using hostinger email accounts, which was fine.

Now, to achieve the same result with React, I've read many articles that pointed me to axios, now everytime I hit that submit button I am seeing a 404 error, can't understand where am I doing wrong.

Here's my App component -

import React from 'react';
import './App.css';
import axios from 'axios';

export default class App extends React.Component {
    state = {
        fname: "", 
        name: "", 
        email: "", 
        message: "", 
        mailSent: false,
        error: null
    };

onFormSubmitSuccess = (e) => {
    e.preventDefault();
    console.log(this.state);

    axios({
        method: 'post',
        url: 'http://localhost/contact/',
        headers: { 'content-type': 'application/json' },
        data: this.state
    })
        .then(result => {
            this.setState({
                mailSent: result.data.sent
            })
        })
        .catch(error => this.setState({ error: error.message }))
}

render() {
    return (
        <div className="App">
            <p>Contact Me</p>
            <div>
                <form action="#">
                    <label>First Name</label>
                    <input type="text" id="fname" name="firstname" placeholder="Your name.."
                        value={this.state.fname}
                        onChange={e => this.setState({ fname: e.target.value })}
                    />

                    <label>Last Name</label>
                    <input type="text" id="lname" name="lastname" placeholder="Your last name.."
                        value={this.state.lname}
                        onChange={e => this.setState({ lname: e.target.value })}
                    />

                    <label>Email</label>
                    <input type="text" id="email" name="email" placeholder="Your email"
                        value={this.state.email}
                        onChange={e => this.setState({ email: e.target.value })}
                    />

                    <label>Message</label>
                    <textarea id="message" name="message" placeholder="Write something.."
                        onChange={e => this.setState({ message: e.target.value })}
                        value={this.state.message}
                    ></textarea>

                    <input type="submit" onClick={e => this.onFormSubmitSuccess(e)} value="Submit" />
                    <div>
                        {this.state.mailSent &&
                            <div className="sucsess">Thank you for contcting me.</div>
                        }
                        {this.state.error &&
                            <div className="error">{this.state.error}</div>
                        }
                    </div>
                </form>
            </div>
        </div>
    );
  }
}

Here's my PHP file -

header("Access-Control-Allow-Origin: *");
$rest_json = file_get_contents("php://input");

$_POST = json_decode($rest_json, true);

if (empty($_POST['fname']) && empty($_POST['email'])) {
print '<br/><b style="color:#B60000">Exception:</b> ';
echo "<br/><b>All fields are required. Please fill all the fields.</b>";
die();
}

//if (isset($_POST["submit"])) {
if ($_POST) {
http_response_code(200);

require 'PHPMailer/PHPMailerAutoload.php';

$mail = new PHPMailer;

$mail->isSMTP();                                    // Set mailer to use SMTP
$mail->Host = 'mx1.hostinger.com';                  // Specify main and backup SMTP servers
$mail->SMTPAuth = true;                             // Enable SMTP authentication
$mail->Username = '<email>';                    // SMTP username
$mail->Password = '<password>';                 // SMTP password
$mail->SMTPSecure = 'true';                         // Enable TLS encryption, `ssl` also accepted
$mail->Port = 587;                                  // TCP port to connect to

$mail->setFrom('fakeuser@domain.com', $name);
$mail->addReplyTo($email, $name);
$mail->addAddress('targetemail@gmail.com');         // Add a recipient

$mail->isHTML(true);  // Set email format to HTML

$bodyContent = "<html>
";
$bodyContent .= "<head>
";
$bodyContent .= "<link href='https://fonts.googleapis.com/css?family=Tajawal' rel='stylesheet'>
";
$bodyContent .= "</head>
";
$bodyContent .= "<body style=\"font-family: 'Tajawal', sans-serif; font-size: 1em; font-style: normal; font-weight: 300; color: #4B4B4B;\">
";
$bodyContent .= "<br/> Hello Admin!<br/><br/> PFB feedback from '$name'.<br/><br/>
";
$bodyContent .= "Email ID: $email <br/> Message: $message <br/>
";
$bodyContent .= "</body>
";
$bodyContent .= "</html>
";


$mail->Subject = 'Feedback - IKwizU';
$mail->Body = $bodyContent;

if (!$mail->send()) {
    echo json_encode(["sent" => false, "message" => "Email could not be sent. <br/>Mailer Error Details - " . $mail->ErrorInfo]);
} else {
    echo json_encode(array(
        "sent" => true
    ));
    //echo "<br/><b>Your message has been sent! Thank you for reaching out to me, I will get back to you ASAP.</b>";
}
}
?>

enter image description here All the time I am seeing a 404 error, which I think is because its unable to access the API.

Thanks in advance.

  • 写回答

0条回答

    报告相同问题?

    悬赏问题

    • ¥15 使用C#,asp.net读取Excel文件并保存到Oracle数据库
    • ¥15 C# datagridview 单元格显示进度及值
    • ¥15 thinkphp6配合social login单点登录问题
    • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
    • ¥15 如何在scanpy上做差异基因和通路富集?
    • ¥20 关于#硬件工程#的问题,请各位专家解答!
    • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
    • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
    • ¥30 截图中的mathematics程序转换成matlab
    • ¥15 动力学代码报错,维度不匹配