POST请求在Postman正常但Flutter无法向000webhost数据库写入数据
问题分析与解决方案
核心问题:PHP未正确处理Flutter发送的JSON格式POST数据
Postman能正常工作,大概率是因为你在Postman里用的是表单编码(x-www-form-urlencoded)发送数据,而Flutter代码里用jsonEncode发送的是JSON格式请求体。PHP默认的$_POST全局变量只解析表单编码的数据,无法直接获取JSON格式的参数,导致filter_request函数取不到值,最终插入数据库失败。
解决方案步骤
1. 修改PHP代码,支持JSON格式输入
替换原有参数获取逻辑,直接读取并解析JSON请求体:
<?php include '../connection.php'; // 开启错误显示 ini_set('display_errors', '1'); ini_set('display_startup_errors', '1'); error_reporting(E_ALL); // 读取JSON请求体 $input = json_decode(file_get_contents('php://input'), true); if (!$input) { echo json_encode(["status" => "Invalid JSON input"]); exit; } // 获取参数(添加空值判断) $studentName = $input['studentname'] ?? null; $studentGrade = $input['studentgrade'] ?? null; $studentNote = $input['studentnote'] ?? null; // 验证必填参数 if (!$studentName || !$studentGrade || !$studentNote) { echo json_encode(["status" => "Missing required parameters (studentname/studentgrade/studentnote)"]); exit; } try { $stmt = $con->prepare( "INSERT INTO `students` (`student_name`, `student_grade`,`student_total_grades`, `student_note`, `student_stars`) VALUES ( ?,?,?,?,?)"); $stmt->execute([$studentName, $studentGrade, $studentGrade, $studentNote, 0]); $count = $stmt->rowCount(); if ($count > 0) { echo json_encode(["status" => "Success"]); } else { echo json_encode(["status" => "Fail: No rows inserted"]); } } catch(PDOException $e) { // 输出具体数据库错误,方便排查 echo json_encode(["status" => "Database Error: " . $e->getMessage()]); } ?>
2. 优化Flutter请求头,避免重复字段
原代码中headers重复设置了Content-Type(大小写不同),可能导致服务器解析异常,简化为:
@override Future<void> addStudent(String name, String grade, String note) async { final url = Uri.parse("https://mystudentsrating.000webhostapp.com/crud/add_student.php"); final http.Response response = await http.post( url, headers: { 'Content-Type': 'application/json;charset=UTF-8', 'Accept': 'application/json', }, body: jsonEncode({ 'studentname': name, 'studentgrade': grade, 'studentnote': note }), ); final result = utf8.decode(response.bodyBytes); final message = jsonDecode(result); if (response.statusCode != 200) throw Exception(message['status']); }
3. 排查000webhost平台限制
如果上述修改后仍无效,检查以下平台设置:
- ModSecurity拦截:登录000webhost控制面板,找到"Security"选项,尝试临时关闭ModSecurity(部分规则会拦截JSON请求)。
- PHP版本兼容性:确保你的PHP版本支持
json_decode(推荐7.4及以上)。 - 数据库权限:确认
connection.php中的数据库账号拥有INSERT权限,且表结构与插入字段匹配(比如student_name是否允许非空)。
内容的提问来源于stack exchange,提问作者Abrar Lasebai
相关产品推荐
相关产品推荐

