使用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.

dougan1330
dougan1330 嘿,我实际上把它搁置了一段时间,但是你的建议是有效的,还有一些我必须设置的变量名称。和允许来源的+1建议不要设置为*非常感谢。
一年多之前 回复
drcmue4619
drcmue4619 附:不要将allow-origin设置为*,除非您真的希望世界上每个网站(或被脚本小子攻击的每个网站)都有机会通过跨域AJAX请求向您的联系表单发送垃圾邮件。将其设置为实际上应该能够合法地提出请求的域。
一年多之前 回复
dqrmkdu25623
dqrmkdu25623 那么,正如错误所示,您需要将“content-type”添加到您从服务器发回的access-control-allow-headers标头值以响应此跨域请求。如果你没有设置那个看起来你可能没有的标题,那么你可能需要设置它:header(“Access-Control-Allow-Headers:”content-type“);.content-typeisCORS中默认不允许使用其中一个标题。更多信息:developer.mozilla.org/en-US/docs/Web/HTTP/Headers/...
一年多之前 回复
doubi4531
doubi4531 我道歉,我通过XAMPP使用Apache,服务器正在端口80上监听。我已经更新了“url字段”,但现在我收到了网络错误,在控制台日志中我看到-“跨源请求被阻止:同源策略不允许在localhost/contact上读取远程资源。(原因:CORS头中缺少令牌“内容类型”-来自CORS预检通道的“访问-控制-允许-头”)。
一年多之前 回复
dongyutan1703
dongyutan1703 什么是PHP服务器设置?您使用的是apache还是其他一些http服务器?它在运行什么端口?服务器日志中有什么?什么是服务器配置?等等
一年多之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐