首页 > 解决方案 > 尝试使用 Angular 7 和 php 发送电子邮件时出现连接错误被拒绝

问题描述

我正在尝试将 Angular 7 中内置的联系表单与 php 后端连接起来以发送表单。当我在我的 contact.component.ts 文件中控制表单数据时,它显示得很好。这是我用来尝试将其发送到我的 Php 文件的内容:

onSubmit(form) { 
    this.apiService.sendEmail(form)
    .subscribe((Contact: Contact[])=>{
      this.contact = Contact;
   });
}
}

我的 api.service.ts 是:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Contact } from './contact';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class ApiService {
  PHP_API_SERVER = "http://127.0.0.1:8080";
  contact: Contact[]

  sendEmail(form): Observable<Contact[]>{
    return this.httpClient.post<Contact[]>(`${this.PHP_API_SERVER}/contact/contactMail.php`, this.contact);
  }
  constructor(private httpClient: HttpClient) { }
}

最后我的 contactMail.php 文件,位于 src/app 的联系人文件夹中是:

 header("Access-Control-Allow-Origin: *");
 header("Access-Control-Request-Headers: GET,POST,OPTIONS,DELETE,PUT");
 header('Access-Control-Allow-Headers: Accept,Accept-Language,Content-Language,Content-Type');
// Get the posted data.
$postdata = file_get_contents("php://input");

if(isset($postdata) && !empty($postdata))
{
  // Extract the data.
  $request = json_decode($postdata);
}
$name = htmlspecialchars($request->name);

$email=htmlspecialchars($request->email);
$phone=htmlspecialchars($request->phone);
$project=htmlspecialchars($request->project);
$notes=htmlspecialchars($request->notes);
$emailTo = "jg@gmail.com";

$to = $emailTo;
$subject = "Correspondence from the Website";
$headers = "From: " .$name. "\r\n";
$body = "Name: ".$name."\n Email: ".$email."\n
Would like info on: " .$project." \nComments: " .$notes." \n";
$body = wordwrap($body,70);
mail($to, $subject, $body, $headers);

$result = array('message'=>"Thank You " .$name." Your request has been sent.");

echo json_encode($result);

当我在本地运行它时,我收到一个错误消息:POST http://127.0.0.1:8080/contact/contactMail.php net::ERR_CONNECTION_REFUSED 我试图自己解决这个问题并阅读了几个教程,但我仍然很难过。任何帮助将不胜感激。

标签: phpangular

解决方案


推荐阅读