PHP结合React发起POST请求报trying to get property of non-object错
报错原因
你遇到的trying to get property of non-object报错,核心是访问对象属性时目标变量不是合法对象,结合你的代码一共有3个触发问题:
create.php中json_decode(file_get_contents("php://input"))解析失败(比如请求体为空、格式不是合法JSON)时会返回null,你没有做任何校验就直接取$data->name、$data->price,直接触发报错product.php里的INSERT SQL语句没有写字符串闭合,存在语法错误,就算参数传对了也会执行失败- React端表单提交逻辑没有阻止默认刷新行为,会导致请求被中途中断,PHP端拿不到完整请求体
修复方案
1. 修复create.php的参数校验逻辑
增加JSON解析结果校验、必填参数校验,避免直接访问空值属性:
<?php header("Access-Control-Allow-Origin: *"); header("Content-Type: application/json; charset=UTF-8"); header("Access-Control-Allow-Methods: POST"); header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With"); include_once '../config/database.php'; include_once '../class/product.php'; $database = new Database(); $db = $database->getConnection(); $item = new Product($db); $rawInput = file_get_contents("php://input"); $data = json_decode($rawInput); // 校验解析结果和必填参数 if (json_last_error() !== JSON_ERROR_NONE || !$data || !isset($data->name) || !isset($data->price)) { http_response_code(400); echo json_encode(["message" => "参数错误,必须提交name和price字段"]); exit; } $item->name = $data->name; $item->price = $data->price; if ($item->createProduct()) { http_response_code(201); echo json_encode("Product created."); } else { http_response_code(500); echo json_encode("Failed to create product."); } ?>
2. 修复product.php的SQL语法错误
补全SQL语句的字符串闭合,修正后的方法代码:
// POST request to create a product. public function createProduct() { $sqlQuery = "INSERT INTO ". $this->db_table ." SET name = :name, price = :price"; $stmt = $this->conn->prepare($sqlQuery); // sanitize data $this->name=htmlspecialchars(strip_tags($this->name)); $this->price=htmlspecialchars(strip_tags($this->price)); // bind data $stmt->bindParam(":name", $this->name); $stmt->bindParam(":price", $this->price); if ($stmt->execute()) { return true; } return false; }
3. 修复React端提交逻辑
阻止表单默认刷新行为,显式指定请求JSON格式,避免请求被中断、格式错误:
const onSubmit = (event) => { // 阻止表单默认提交刷新 event.preventDefault(); const product = { name: state.name, price: state.price, } console.log(product) axios.post('http://localhost:8080/api/create.php', product, { headers: { 'Content-Type': 'application/json' } }) .then(response => { if (response.data) { setProducts([...products, product]) } }) .catch(error => { console.log(error); }) }
验证要点
改完后按顺序检查:
- 浏览器控制台打印的
product对象,name和price字段都有有效值,不是undefined - 浏览器网络面板中POST请求的请求体是合法JSON,
Content-Type为application/json - 接口不再报non-object错误,数据能正常插入数据库
内容的提问来源于stack exchange,提问作者alizoubair
相关产品推荐
相关产品推荐

