【发布时间】:2020-05-31 22:12:27
【问题描述】:
我可以使用邮递员的 php 端点。我尝试从 angular post 中执行相同操作,但出现此错误 - 解析期间 Http 失败。尽管对我来说一切看起来都很完美,但问题却令人惊讶。这是我的sn-p
php 文件
<?php
header('Access-Control-Allow-Origin: *');
// check for post
if ($_SERVER['REQUEST_METHOD']=='POST') {
$name = $_POST['name'];
$email = $_POST['email'];
$subject = $_POST['subject'];
$message = $_POST['message'];
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$conn = new db_CONNECT();
$cone=$conn->con;
//escpae the strings to be inserted to DB
$escapedname = mysqli_real_escape_string($cone, $name);
$escapedemail = mysqli_real_escape_string($cone, $email);
$escapedsubject= mysqli_real_escape_string($cone, $subject);
$escapedmessage = mysqli_real_escape_string($cone, $message);
// mysql inserting a new row
$sql = "INSERT INTO contacts(name, email, subject, message) VALUES ('$escapedname', '$escapedemail', '$escapedsubject', '$escapedmessage')";
// $result= $cone -> query($sql);
// $affected = $cone -> affected_rows;
if (mysqli_query($cone,$sql)) {
echo "Information saved successfully.";
} else {
echo "Not successful";
}
} else {
echo "Some field missing.";
}
?>
这里是角度 sn-p
saveContactDetails = function () {
this.proceed = true;
this.success = false;
const myheader = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded');
data.append('name', this.contactDeJson.name);
data.append('email', this.contactDeJson.email);
data.append('subject', this.contactDeJson.subject);
data.append('message', this.contactDeJson.message);
this.http
.post('http://localhost:80/'+'api/create_contact.php', data.toString(), {headers: myheader})
请问为什么会出现这个错误
{"headers":{"normalizedNames":{},"lazyUpdate":null},"status":200,"statusText":"OK","url":"http://localhost/api/create_contact.php","ok":false,"name":"HttpErrorResponse","message":"Http failure during parsing for http://localhost/api/create_contact.php",
【问题讨论】:
-
你能把
data在函数里发一下吗? -
表示追加的数据是字符串格式,来自data.append...
-
在开发工具中检查响应是否正常?在我看来,Angular 期待一个 json 响应(默认响应类型),但没有收到正确的数据或标头。
-
在实现到 angular/php 之前,我使用邮递员进行了测试。但你可以建议你的方法,
-
邮递员不验证我认为的响应类型。只需尝试从后端发送内容类型标头,或将 responseType 设置为角度请求中的文本