Flutter项目中向JSON API提交数据时出现400 Bad Request错误的排查求助
解决Flutter POST请求400 Bad Request的问题
嘿,我来帮你排查这个400错误的问题~ 看了你的代码和错误信息,主要有两个关键问题导致服务器无法理解你的请求:
1. 错误的请求头配置
你在请求里添加的Access-Control-*系列头完全没必要,这些是服务器端需要返回的响应头,不是客户端要发送的请求头,乱加反而会让服务器困惑。另外,你把Content-Type拼写成了ContentType(少了中间的横杠),这会导致服务器识别不出你发送的是JSON格式的数据。
2. 请求Body没有序列化为JSON字符串
http.post方法如果直接传Map类型的body,默认会用application/x-www-form-urlencoded格式发送,但你的API应该是期望JSON格式的,所以必须把Map转换成JSON字符串。
修正后的代码
// 记得先导入dart:convert包 import 'dart:convert'; import 'package:http/http.dart' as http; save() async { try{ var sendData = { 'userId': userId, 'userEmail': userEmail, }; final response = await http.post( Uri.parse('http://localhost:5000/createapp'), headers: <String, String>{ // 只保留正确的Content-Type头 "Content-Type": 'application/json; charset=UTF-8', }, // 将Map转换为JSON字符串 body: jsonEncode(sendData), ); print(response.body); }catch(e){ print(e); } }
额外提醒
如果之后遇到跨域相关的错误(比如CORS blocked),不要在客户端加请求头,而是去配置你的后端服务器:
- 比如用Node.js+Express的话,安装
cors包并启用; - 用Flask的话,安装
flask-cors扩展; - 确保服务器允许来自Flutter运行地址(比如
http://localhost:5000或者你的真机IP)的请求。
内容的提问来源于stack exchange,提问作者beatfloraminederecho
相关产品推荐
相关产品推荐

