Flutter Post请求未向服务器发送Body参数问题求助
Flutter Post请求参数无法传递至服务器的排查方案
请求内容类型不匹配
默认情况下,http.post传入Map类型的body时,会使用application/x-www-form-urlencoded编码。如果服务器端期望接收application/json格式的参数,就会解析失败导致参数为null。解决方式是显式设置请求头,并将参数转为JSON字符串:Future<void> listRecentCashTransactions() async{ try{ var res = await http.post( Uri.parse(API.recentCashTransactionURL), headers: {'Content-Type': 'application/json'}, body: jsonEncode({ 'userID': userID.toString(), 'sessionData': sessionData.toString(), }), ); if(res.statusCode==200){ final resBody = jsonDecode(res.body); final sessionDataX = resBody['checkSessionData']; int userXID = resBody['checkUserID']; print("User ID before API call : $userID"); print("User ID after API call : $userXID"); print("Session Data before API call : $sessionData"); print("Session data after : $sessionDataX"); } } catch(e){ print(e.toString()); } }服务器端参数名称不匹配
核对服务器端接收参数的名称是否和你传递的userID、sessionData完全一致,注意大小写、拼写差异(比如服务器端用user_id而非userID)。参数未正确初始化
确认调用该方法前,userID和sessionData已被正确赋值,而非null。可以在发送请求前添加打印验证:print("userID value: $userID"); print("sessionData value: $sessionData");接口URL错误
检查API.recentCashTransactionURL指向的服务器端点是否正确,避免拼写错误或指向了错误的接口路径。
内容的提问来源于stack exchange,提问作者Cliff Odebala Clarke
相关产品推荐
相关产品推荐

