React Axios Delete请求报错,PHP API提示id非对象问题排查修复
问题:React调用PHP Delete接口时出现
Trying to get property 'id' of non-object错误 通过Postman测试所有PHP接口均正常,但使用React前端调用Delete接口时,始终报错:
<br /> <b>Notice</b>: Trying to get property 'id' of non-object in <b>C:\xampp\htdocs\mypost\api\delete.php</b> on line <b>22</b><br /> {"message":"Post Deleted"}
即使硬编码ID仍出现相同错误,无法定位问题。
相关代码
React 删除组件
import { useEffect } from "react"; import axios from "axios"; import { useNavigate, useParams } from "react-router-dom"; export default function Delete(){ const navigate = useNavigate(); const { id } = useParams(); const hardcode = {"id":11}; useEffect(() => { deletePost(); },[]); // 目前使用硬编码ID,但依然报错 const deletePost = () => { axios.delete('http://localhost:8081/mypost/api/delete.php', {"id":11}) .then(res => { console.log(res.data) navigate('/read'); }).catch(err => console.log(err)) } return( <h1>Delete my Post</h1> ) }
PHP Delete接口代码
<?php // Headers header('Access-Control-Allow-Origin: *'); header('Content-Type: application/json'); header('Access-Control-Allow-Methods: DELETE'); header('Access-Control-Allow-Headers: Access-Control-Allow-Headers,Content-Type,Access-Control-Allow-Methods, Authorization, X-Requested-With'); include_once '../config/Database.php'; include_once '../models/Post.php'; // Instantiate DB & connect $database = new Database(); $db = $database->connect(); // Instantiate blog post object $post = new Post($db); // Get raw posted data $data = json_decode(file_get_contents("php://input")); // Set ID to update $post->id = $data->id; // Delete post if($post->delete()) { echo json_encode( array('message' => 'Post Deleted') ); } else { echo json_encode( array('message' => 'Post Not Deleted') ); } ?>
问题原因及解决方案
核心问题
axios.delete()的参数传递方式错误。axios的delete方法第二个参数是配置对象,如果要发送请求体数据,必须把数据放在data字段中,而不是直接传递数据对象。你当前的写法没有将ID放入请求体,导致PHP端file_get_contents("php://input")获取不到JSON数据,json_decode后返回null,自然会触发Trying to get property 'id' of non-object的错误。
修复后的React代码
修改deletePost函数,将ID放入data字段:
const deletePost = () => { axios.delete('http://localhost:8081/mypost/api/delete.php', { data: {"id": 11} // 关键:将数据放在data字段中 }) .then(res => { console.log(res.data) navigate('/read'); }).catch(err => console.log(err)) }
额外优化(可选)
为了避免PHP端因$data为null导致的错误,建议在PHP代码中增加校验:
// Get raw posted data $data = json_decode(file_get_contents("php://input")); // 校验ID是否存在 if(!isset($data->id) || empty($data->id)) { echo json_encode(array('message' => 'Invalid or missing post ID')); exit; } // Set ID to update $post->id = $data->id;
内容的提问来源于stack exchange,提问作者user3528204
相关产品推荐
相关产品推荐

