我正在执行的测试 api 发布请求有问题。我有一个发布请求,在我收到 404 状态代码之前,但现在是 400。我测试它的方式是我使用本地 api,您可以在我的发布功能的 url 中看到它。我认为 400 错误是由于我传递的数据没有像我将空值传递给 api 那样通过 api 引起的,但我不太确定所以我不知道是什么问题。
我可以很好地在表格中添加数据,我首先解决了连接问题,因为我无法将它连接到另一台电脑,我可以通过让其他设备发现电脑来解决它。但剩下的问题是它返回错误 400,我认为这是因为数据的传递,但我不确定我的代码中是否还有其他问题。
这是带有 post 函数的 dart 文件:
import 'dart:convert';
import 'package:audit_finance_app/widgets/registration_widgets.dart';
import 'package:audit_finance_app/widgets/widgets.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:http/http.dart';
import '../models/user_info.dart';
class Registration extends StatefulWidget {
const Registration({super.key});
@override
State<Registration> createState() => _RegistrationState();
}
class _RegistrationState extends State<Registration> {
final firstNameController = TextEditingController();
final lastNameController = TextEditingController();
final birthdayController = TextEditingController();
final genderController = TextEditingController();
final mobileController = TextEditingController();
final _formKey = GlobalKey<FormState>();
RegistrationInfo registrationInfo = RegistrationInfo();
Future<void> registerUser(RegistrationInfo registrationInfo) async {
final url =
Uri.parse('http://192.168.100.228/api/v1/index.php/registration');
// var uri = Uri.https('192.168.100.228', 'api/v1/index.php/registration');
try {
final response = await post(
url,
body: json.encode(
registrationInfo.toJson(),
),
);
if (response.statusCode == 200) {
print('User registered successfully!');
} else {
print('Failed to register user. Status code: ${response.statusCode}');
}
} catch (e) {}
}
void getTextFormFieldValue() {
registrationInfo.first_name = firstNameController.text;
registrationInfo.last_name = lastNameController.text;
registrationInfo.birthday = birthdayController.text;
registrationInfo.gender = genderController.text;
registrationInfo.mobile = mobileController.text;
print(registrationInfo.first_name);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('REGISTRATION'),
centerTitle: true,
),
body: Padding(
padding: const EdgeInsets.fromLTRB(30, 15, 30, 0),
child: Column(
children: [
Form(
key: _formKey,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Widgets().sizedBoxHeight(15),
RegistrationWidgets().label(text: 'First Name'),
Widgets().sizedBoxHeight(5),
RegistrationWidgets().textField(
textEditingController: firstNameController,
hint: 'Please enter your first name',
),
Widgets().sizedBoxHeight(15),
RegistrationWidgets().label(text: 'Last Name'),
Widgets().sizedBoxHeight(5),
RegistrationWidgets().textField(
textEditingController: lastNameController,
hint: 'Please enter your last name',
),
Widgets().sizedBoxHeight(15),
RegistrationWidgets().label(text: 'Birthday'),
Widgets().sizedBoxHeight(5),
RegistrationWidgets().textField(
textEditingController: birthdayController,
hint: 'Please enter your birthday',
),
Widgets().sizedBoxHeight(15),
RegistrationWidgets().label(text: 'Gender'),
Widgets().sizedBoxHeight(5),
RegistrationWidgets().textField(
textEditingController: genderController,
hint: 'Please enter your gender',
),
Widgets().sizedBoxHeight(15),
RegistrationWidgets().label(text: 'Mobile Number'),
Widgets().sizedBoxHeight(5),
RegistrationWidgets().textField(
textEditingController: mobileController,
hint: 'Please enter you mobile number',
),
],
),
),
Widgets().sizedBoxHeight(20),
FilledButton(
onPressed: () {
if (_formKey.currentState!.validate()) {
// do something
// Navigator.pop(
// context,
// MaterialPageRoute(
// builder: (context) => const LogIn(),
// ),
// );
// print(firstNameController.text);
// print(lastNameController.text);
// print(birthdayController.text);
// print(genderController.text);
// print(mobileController.text);
getTextFormFieldValue();
registerUser(registrationInfo);
Fluttertoast.showToast(
toastLength: Toast.LENGTH_SHORT,
msg: 'Registration complete',
gravity: ToastGravity.BOTTOM_LEFT,
backgroundColor: Colors.grey,
);
// print('YOU ARE REGISTERED');
}
},
style: FilledButton.styleFrom(
minimumSize: const Size.fromHeight(50),
),
child: const Text('Register'),
),
],
),
),
);
}
}
这是模型:
class RegistrationInfo {
String? first_name;
String? last_name;
String? birthday;
String? gender;
String? mobile;
RegistrationInfo(
{this.first_name,
this.last_name,
this.birthday,
this.gender,
this.mobile});
RegistrationInfo.fromJson(Map<String, dynamic> json) {
first_name = json['first_name'];
last_name = json['last_name'];
birthday = json['birthday'];
gender = json['gender'];
mobile = json['mobile number'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = <String, dynamic>{};
data['first_name'] = first_name;
data['last_name'] = last_name;
data['birthday'] = birthday;
data['gender'] = gender;
data['mobile number'] = mobile;
return data;
}
}
这是api文档:
$app->post('/registration', function () use ($app){
//Required Parameters
verifyRequiredParams(array('first_name','last_name','birthday','gender','mobile'));
//includes
$database = new Database();
$conn = $database->getConnection();
//
$db = new SaveInfo($conn);
$response = array();
$first_name = $app->request->post('first_name');
$last_name = $app->request->post('last_name');
$birthday = $app->request->post('birthday');
$gender = $app->request->post('gender');
$mobile = $app->request->post('mobile');
$result = $db->savePersonalInfo($first_name,$last_name,$birthday,$gender,$mobile);
if($result){
$response['error'] = false;
$response['message'] = "Successfully Registered";
}
else{
$response['error'] = true;
$response['message'] = "Failed to register";
}
echoResponse(200,$response);
});
这里是工作邮递员要求:
这是 404 的错误消息
{“error”:true,“message”:“必填字段 first_name,last_name, birthday, gender, mobile is missing or empty"} 注册失败 用户。状态码:400
在邮递员屏幕截图中,您似乎正在使用表单数据。你不需要对你的身体进行 json 编码。
final response = await post(
url,
body: registrationInfo.toJson(),
);
This answer might help you further - How make a http post using form data in flutter?