您似乎陷入了 Angular 和 PHP 之间的接口 - 这是可以理解的,因为它不像通过访问变量那么简单$_POST
超全球。
默认情况下,Angular 将请求正文中传递给它的数据作为json字符串,因此您必须访问原始请求正文并将其解析为可用的 PHP 变量。
以下示例显示了无需额外框架或其他依赖项即可执行此操作的最基本方法。您可以(并且应该)遵循更好的组织实践并将这些内容移动到服务中,但这会增加一层不需要的复杂性:
import { Component, OnInit } from '@angular/core';
import {Http} from "@angular/http";
@Component({
selector: 'app-mailer',
template: '<button (click)="sendEmail()">Send the Email</button>'
})
export class MailerComponent implements OnInit {
email : string;
name : string;
message : string;
endpoint : string;
http : Http;
constructor(http : Http) {
this.http = http;
}
ngOnInit() {
//This data could really come from some inputs on the interface - but let's keep it simple.
this.email = "[email protected] /cdn-cgi/l/email-protection";
this.name = "Hayden Pierce";
this.message = "Hello, this is Hayden.";
//Start php via the built in server: $ php -S localhost:8000
this.endpoint = "http://localhost:8000/sendEmail.php";
}
sendEmail(){
let postVars = {
email : this.email,
name : this.name,
message : this.message
};
//You may also want to check the response. But again, let's keep it simple.
this.http.post(this.endpoint, postVars)
.subscribe(
response => console.log(response),
response => console.log(response)
)
}
}
还有 PHP 脚本。请注意,这会检查多个请求方法。它还检查 OPTIONS 请求。看看为什么这是必要的 https://stackoverflow.com/questions/20035101/no-access-control-allow-origin-header-is-present-on-the-requested-resource.
为了使其尽可能简单,我已经跳过了对输入的清理来自 Angular,这被认为是一个严重的安全问题。您应该将其添加到面向生产的应用程序中:
<?php
switch($_SERVER['REQUEST_METHOD']){
case("OPTIONS"): //Allow preflighting to take place.
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Allow-Headers: content-type");
exit;
case("POST"): //Send the email;
header("Access-Control-Allow-Origin: *");
$json = file_get_contents('php://input');
$params = json_decode($json);
$email = $params->email;
$name = $params->name;
$message = $params->message;
$recipient = '[email protected] /cdn-cgi/l/email-protection';
$subject = 'new message';
$headers = "From: $name <$email>";
mail($recipient, $subject, $message, $headers);
break;
default: //Reject any non POST or OPTIONS requests.
header("Allow: POST", true, 405);
exit;
}