использование React - Axios для доставки mgs / mail с PHP - PullRequest
1 голос
/ 15 мая 2019

Я переделываю свой текущий портфель с HTML на React.Итак, моя контактная форма поддерживается PHP, из которого я использую функцию mail для отправки электронной почты с использованием учетных записей электронной почты hostinger, что было хорошо.

Теперь, чтобы достичь того же результата с React, я прочитал много статейэто указало мне на axios, теперь каждый раз, когда я нажимаю кнопку подтверждения, я вижу ошибку 404, не могу понять, где я делаю неправильно.

Вот мой компонент приложения -

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>
    );
  }
}

Вот мой PHP-файл -

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


$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 Все время я вижу ошибку 404, которая, по-моему, связана с невозможностью доступа к API.

Спасибо завперед.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...