Angular12结合PHPMailer发送表单出现Http解析错误该如何解决
问题根源
你遇到的解析报错是Angular HttpClient默认会将响应内容按JSON格式解析,但你的PHP接口返回的是纯文本字符串,解析失败就触发了这个错误,同时你还存在前后端数据格式不匹配的问题。
解决步骤
1. Angular端配置响应类型为text
修改你的服务代码,添加responseType: 'text'配置指定响应为文本格式,修改后的代码如下:
import { Injectable } from '@angular/core'; import { Observable, of, from } from 'rxjs'; import { HttpClient, HttpHeaders } from '@angular/common/http'; import { catchError, map, tap } from 'rxjs/operators'; import { environment } from '../../environments/environment'; // 新增responseType配置 const httpOptions = { headers: new HttpHeaders({'Content-Type':'application/json'}), responseType: 'text' as const }; @Injectable({ providedIn: 'root' }) export class MycontactService { apiUrl = environment.apiUrl; emailUrl = environment.emailUrl; constructor(private http:HttpClient) { } private handleError<T>(operation = 'operation', result?: T) { return (error: any): Observable<T> => { console.error(error); console.log(`${operation} failed: ${error.message}`); return of(result as T); } } // 修改post方法的泛型定义,适配文本返回值 sendMessage(landingForm:any): Observable<string> { return this.http.post(`${this.emailUrl}`, landingForm, httpOptions).pipe( tap(message => console.log(message)), catchError(this.handleError<string>('Sending', '发送失败')) ); } }
2. 修复PHP端接收数据的问题
你Angular端发送的是application/json格式的请求,PHP默认的$_POST全局变量只能接收application/x-www-form-urlencoded格式的请求数据,所以你目前PHP无法正确拿到表单提交的内容,需要修改PHP代码读取原始请求体解析JSON:
<?php // 可选:如果存在跨域问题可以添加以下两行头配置 header("Access-Control-Allow-Origin: *"); header("Content-Type: text/plain; charset=utf-8"); require 'includes/PHPMailer.php'; require 'includes/SMTP.php'; require 'includes/Exception.php'; use PHPMailer\PHPMailer\Exception; use PHPMailer\PHPMailer\PHPMailer; use PHPMailer\PHPMailer\SMTP; // 读取JSON格式的请求体 $rawData = file_get_contents('php://input'); $postData = json_decode($rawData, true); // 从解析后的数组中读取参数,不要使用$_POST if(isset($postData['nombre']) && isset($postData['email']) && isset($postData['mensaje'])){ $nombre = $postData['nombre']; $email = $postData['email']; $mensaje = $postData['mensaje']; }else{ echo "参数缺失"; exit; } $mail = new PHPMailer(true); try{ //Server settings $mail->SMTPDebug = false; $mail->Host = 'smtp.gmail.com'; $mail->SMTPAuth = true; $mail->Username = 'kanazawa8213@gmail.com'; $mail->Password = '*******'; // 端口587对应STARTTLS加密,SMTPS加密对应端口465,这里修正避免发送失败 $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS; $mail->Port = 587; //Recipients $mail->setFrom('kanazawa8213@gmail.com', 'Ptree'); $mail->addAddress('kanazawa8213@gmail.com'); //Content $mail->isHTML(true); $mail->Subject = 'Nuevo mensaje desde Ptree site'; $mail->Body = "Este es un mensaje desde Ptree site:\n\n". " Nombre: " .$nombre. "\n\n Email: " .$email. "\n\n Mensaje: " .$mensaje; $mail->send(); echo 'Message has been sent'; }catch (Exception $e) { echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}"; } ?>
3. 其他可能的问题排查点
- 谷歌邮箱SMTP需要开启第三方应用访问权限,或者配置应用专用密码,否则会被系统拦截导致发送失败
- 检查PHPMailer引入的文件路径是否正确,避免文件不存在触发报错
- 若前端和接口域名不同,需要在PHP端配置对应跨域头,允许你的前端域名访问
内容的提问来源于stack exchange,提问作者Luis Alejandro López de Anda
相关产品推荐
相关产品推荐

