我正在学习如何使用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;
这让我想到这个问题与我的代码有关。
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
我真的不知道我做错了什么。这方面似乎没有任何文件。或者如果是的话,通常都太抽象了。任何帮助都将不胜感激!
1条答案
按热度按时间v1uwarro1#
从https://developer.mozilla.org/en-us/docs/web/http/methods/post
application/x-www-form-urlencoded:键和值在键值元组中编码,元组之间用“&”分隔,键和值之间用“=”。键和值中的非字母数字字符都是百分比编码的:这就是为什么这种类型不适合用于二进制数据的原因(改用多部分/表单数据)
将内容类型从application/x-www-form-urlencoded更改为multipart/form data
还要检查这个非常有用的线程:application/x-www-form-urlencoded还是multipart/formdata?