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条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥100 c语言,请帮蒟蒻看一个题
    • ¥15 名为“Product”的列已属于此 DataTable
    • ¥15 安卓adb backup备份应用数据失败
    • ¥15 eclipse运行项目时遇到的问题
    • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
    • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
    • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
    • ¥50 成都蓉城足球俱乐部小程序抢票
    • ¥15 yolov7训练自己的数据集
    • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)