gpt4 book ai didi

php - 使用 Angular 将 Post 发送到 PHP 文件

转载 作者:行者123 更新时间:2023-11-29 06:40:58 25 4
gpt4 key购买 nike

我正在学习如何使用 HttpClient.post 更新 MySQL 数据库。我要插入的表是:

|id - 日志|

PHP文件如下,

<?php 
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Headers: X-Requested-With');
header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
include 'db.php';

$postdata=file_get_contents("php://input");
$request = json_decode($postdata);
$message = $request->message;

// Create connection
$conn = new mysqli($server_name, $mysql_username, $mysql_password, $db_name);


$sql = "INSERT INTO shootingchatlog (id, log) VALUES (NULL, '$message')";

if($conn -> query($sql) === TRUE ){
echo "message Uploaded Successfully";
}else{
echo "Error Uploading Image";
}
mysqli_close($conn);

我不断收到错误消息

$message = $request->message;

这让我认为问题与我的 Angular 代码有关。

   httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json'
})
};



constructor(private http: HttpClient) { }


public uploadService(mess: string): void {
console.log(mess);
this.http.post(this.url, JSON.stringify({"messasge": mess}), this.httpOptions)
.subscribe((res: Response) => {
console.log(res);
},
err => {
console.log("Error occured", err);
});
}

我遇到的最常见错误是:

SyntaxError: Unexpected token < in JSON at position 0 at JSON.parse

我真的不确定我做错了什么。似乎没有任何关于此的文档。或者即使是这样,它通常也太抽象了。任何帮助将不胜感激!

最佳答案

来自 https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST

application/x-www-form-urlencoded: the keys and values are encoded in key-value tuples separated by '&', with a '=' between the key and the value. Non-alphanumeric characters in both keys and values are percent encoded: this is the reason why this type is not suitable to use with binary data (use multipart/form-data instead)

将内容类型从 application/x-www-form-urlencoded 更改为 multipart/form-data

还要检查这个非常有帮助的线程:application/x-www-form-urlencoded or multipart/form-data?

关于php - 使用 Angular 将 Post 发送到 PHP 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51637803/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com