我已经完成了表单,并且能够使用状态捕获我的输入(使用react),但是提交时,我的控制台出现以下错误:
POST http://localhost:3000/my-web-app/src/api/contact/index.php 404 (Not Found)
我目前仍在开发Web应用程序,我认为问题可能是因为我在本地主机上,所以我尝试将index.php文件上传到服务器,当我尝试这样做时,出现以下错误:< / p>
Access to XMLHttpRequest at 'https://website.ca/index.php' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
我尝试将标头添加到我的php文件中,但似乎没有任何改变...
这是我的帖子请求的样子:
handleFormSubmit = e => {
e.preventDefault();
axios({
method: 'post',
url: `${API_PATH}`,
headers: { 'content-type': 'application/json' },
data: this.state
})
.then(result => {
this.setState({
mailSent: result.data.sent
})
})
.catch(error => this.setState({ error: error.message }));
};
这是我的index.php文件(仅用于发送简单的电子邮件):
<?php
header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE");
header("Access-Control-Allow-Headers: Authorization");
$rest_json = file_get_contents("php://input");
$_POST = json_decode($rest_json, true);
if (empty($_POST['fname']) && empty($_POST['email'])) die();
if ($_POST)
{
// set response code - 200 OK
http_response_code(200);
$subject = $_POST['fname'];
$to = "info@cannections.ca";
$from = $_POST['email'];
// data
$msg = $_POST['number'] . $_POST['message'];
// Headers
$headers = "MIME-Version: 1.0\r\n";
$headers.= "Content-type: text/html; charset=UTF-8\r\n";
$headers.= "From: <" . $from . ">";
mail($to, $subject, $msg, $headers);
// echo json_encode( $_POST );
echo json_encode(array(
"sent" => true
));
}
else
{
// tell the user about error
echo json_encode(["sent" => false, "message" => "Something went wrong"]);
}
?>
我从未部署过react.js应用程序(还),但我不知道此问题是否仅是由于本地主机引起的,无论它们在哪里(浏览器),无论哪种方式,我都需要此电子邮件才能工作……等等。感谢您可以从中获得的所有帮助!
干杯。