我有 Angular2+ 应用程序,它使用 PHP 作为服务器端。我需要将数据发送到 PHP 脚本,它将处理数据并创建一个文件,然后将该文件发送到管理员的邮件并向前端响应消息已发送(或在其他情况下出现错误) 。这是我的一些代码:Angular2+
submit() {
this.http.post('https://myWeb.site/script.php', this.dataService.sharedData)
.subscribe(response => {
if (response == "Message sent!"){
//Do something
}
})
}
PHP
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: Content-Type, origin");
require 'vendor/autoload.php';
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
$vars = get_angular_request_payload();
function get_angular_request_payload() {
return json_decode(file_get_contents('php://input'), true);
}
//(some data processing and .xlsx file configuration)
$writer = new Xlsx($spreadsheet);
$fileName = 'NewOrder.xlsx';
$writer->save($fileName);
$mail = new PHPMailer();
$mail->isSMTP();
$mail->Host = 'smtp.gmail.com';
$mail->Port = 587;
$mail->SMTPSecure = 'tsl';
$mail->SMTPAuth = true;
$mail->Username = "somemail@gmail.com";
$mail->Password = "somepassword";
$mail->setFrom('somemail@some.com', 'sale.some.com');
$mail->addAddress('tomail@gmail.com', 'CompanyName');
$mail->Subject = 'New order';
$mail->Body = 'My Text';
$mail->CharSet = 'UTF-8';
$file_to_attach = './NewOrder.xlsx';
$mail->AddAttachment( $file_to_attach , 'New.xlsx' );
$mail->send();
echo json_encode('Message sent!', true);//response
问题是,有时它会向管理员发送邮件,但 Angular 没有得到任何响应,有时它工作得很好。我尝试在第一行移动响应(只是为了检查它是否有效),但没有帮助。
也许有人有什么建议?
绝地无双