HTTP POST请求返回状态码400。

huangapple go评论61阅读模式
英文:

http post request returns status code 400

问题

我遇到了我正在进行的测试API POST请求的问题。我有一个POST请求,在之前我收到的状态码是404,但现在是400。我测试的方式是使用本地API,您可以在我的POST函数的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');
    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 your mobile number',
                  ),
                ],
              ),
            ),
            Widgets().sizedBoxHeight(20),
            FilledButton(
              onPressed: () {
                if (_formKey.currentState!.validate()) {
                  getTextFormFieldValue();
                  registerUser(registrationInfo);
                  Fluttertoast.showToast(
                    toastLength: Toast.LENGTH_SHORT,
                    msg: 'Registration complete',
                    gravity: ToastGravity.BOTTOM_LEFT,
                    backgroundColor: Colors.grey,
                  );
                }
              },
              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);
});

这是可工作的Postman请求。

希望这对您有所帮助!如果您有其他问题,请

英文:

I'm having a problem with the test api post request that I'm doing. I have a post request and before I am receiving a status code of 404 but now it is 400. The way I am testing it is that I am using a local api, you can see it in the url in my post function. I think the 400 error is caused by the data that I am passing is not going through the api like I am passing a null value to the api, but I im not really sure so I dont know what is the problem.

I can add data in the table just fine and I solved the connection problem at first because I cannot connect it to the other pc and I am able to solve it by making the pc discoverable by other devices. but the remaining problem is that it returns error 400, and I think it is because of the passing of data but Im not entriely sure if there is other problem in my code.

Here is the dart file with the post function:

import &#39;dart:convert&#39;;
import &#39;package:audit_finance_app/widgets/registration_widgets.dart&#39;;
import &#39;package:audit_finance_app/widgets/widgets.dart&#39;;
import &#39;package:flutter/material.dart&#39;;
import &#39;package:fluttertoast/fluttertoast.dart&#39;;
import &#39;package:http/http.dart&#39;;
import &#39;../models/user_info.dart&#39;;
class Registration extends StatefulWidget {
const Registration({super.key});
@override
State&lt;Registration&gt; createState() =&gt; _RegistrationState();
}
class _RegistrationState extends State&lt;Registration&gt; {
final firstNameController = TextEditingController();
final lastNameController = TextEditingController();
final birthdayController = TextEditingController();
final genderController = TextEditingController();
final mobileController = TextEditingController();
final _formKey = GlobalKey&lt;FormState&gt;();
RegistrationInfo registrationInfo = RegistrationInfo();
Future&lt;void&gt; registerUser(RegistrationInfo registrationInfo) async {
final url =
Uri.parse(&#39;http://192.168.100.228/api/v1/index.php/registration&#39;);
// var uri = Uri.https(&#39;192.168.100.228&#39;, &#39;api/v1/index.php/registration&#39;);
try {
final response = await post(
url,
body: json.encode(
registrationInfo.toJson(),
),
);
if (response.statusCode == 200) {
print(&#39;User registered successfully!&#39;);
} else {
print(&#39;Failed to register user. Status code: ${response.statusCode}&#39;);
}
} 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(&#39;REGISTRATION&#39;),
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: &#39;First Name&#39;),
Widgets().sizedBoxHeight(5),
RegistrationWidgets().textField(
textEditingController: firstNameController,
hint: &#39;Please enter your first name&#39;,
),
Widgets().sizedBoxHeight(15),
RegistrationWidgets().label(text: &#39;Last Name&#39;),
Widgets().sizedBoxHeight(5),
RegistrationWidgets().textField(
textEditingController: lastNameController,
hint: &#39;Please enter your last name&#39;,
),
Widgets().sizedBoxHeight(15),
RegistrationWidgets().label(text: &#39;Birthday&#39;),
Widgets().sizedBoxHeight(5),
RegistrationWidgets().textField(
textEditingController: birthdayController,
hint: &#39;Please enter your birthday&#39;,
),
Widgets().sizedBoxHeight(15),
RegistrationWidgets().label(text: &#39;Gender&#39;),
Widgets().sizedBoxHeight(5),
RegistrationWidgets().textField(
textEditingController: genderController,
hint: &#39;Please enter your gender&#39;,
),
Widgets().sizedBoxHeight(15),
RegistrationWidgets().label(text: &#39;Mobile Number&#39;),
Widgets().sizedBoxHeight(5),
RegistrationWidgets().textField(
textEditingController: mobileController,
hint: &#39;Please enter you mobile number&#39;,
),
],
),
),
Widgets().sizedBoxHeight(20),
FilledButton(
onPressed: () {
if (_formKey.currentState!.validate()) {
// do something
// Navigator.pop(
//   context,
//   MaterialPageRoute(
//     builder: (context) =&gt; 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: &#39;Registration complete&#39;,
gravity: ToastGravity.BOTTOM_LEFT,
backgroundColor: Colors.grey,
);
// print(&#39;YOU ARE REGISTERED&#39;);
}
},
style: FilledButton.styleFrom(
minimumSize: const Size.fromHeight(50),
),
child: const Text(&#39;Register&#39;),
),
],
),
),
);
}
}

Here is the model:

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&lt;String, dynamic&gt; json) {
first_name = json[&#39;first_name&#39;];
last_name = json[&#39;last_name&#39;];
birthday = json[&#39;birthday&#39;];
gender = json[&#39;gender&#39;];
mobile = json[&#39;mobile number&#39;];
}
Map&lt;String, dynamic&gt; toJson() {
final Map&lt;String, dynamic&gt; data = &lt;String, dynamic&gt;{};
data[&#39;first_name&#39;] = first_name;
data[&#39;last_name&#39;] = last_name;
data[&#39;birthday&#39;] = birthday;
data[&#39;gender&#39;] = gender;
data[&#39;mobile number&#39;] = mobile;
return data;
}
}

This is the api documentation:

$app-&gt;post(&#39;/registration&#39;, function () use  ($app){
//Required Parameters
verifyRequiredParams(array(&#39;first_name&#39;,&#39;last_name&#39;,&#39;birthday&#39;,&#39;gender&#39;,&#39;mobile&#39;));
//includes
$database = new Database();
$conn = $database-&gt;getConnection();
//
$db = new SaveInfo($conn);
$response = array();
$first_name = $app-&gt;request-&gt;post(&#39;first_name&#39;);
$last_name = $app-&gt;request-&gt;post(&#39;last_name&#39;);
$birthday = $app-&gt;request-&gt;post(&#39;birthday&#39;);
$gender = $app-&gt;request-&gt;post(&#39;gender&#39;);
$mobile = $app-&gt;request-&gt;post(&#39;mobile&#39;);
$result = $db-&gt;savePersonalInfo($first_name,$last_name,$birthday,$gender,$mobile);
if($result){
$response[&#39;error&#39;] = false;
$response[&#39;message&#39;] = &quot;Successfully Registered&quot;;
}
else{
$response[&#39;error&#39;] = true;
$response[&#39;message&#39;] = &quot;Failed to register&quot;;
}
echoResponse(200,$response);
});

Here is the working postman request:

HTTP POST请求返回状态码400。

This is the error message for the 404

> {"error":true,"message":"Required field(s) first_name, last_name,
> birthday, gender, mobile is missing or empty"} Failed to register
> user. Status code: 400

答案1

得分: 1

在Postman截图中,您似乎正在使用form-data。您不需要对请求主体进行JSON编码。

final response = await post(
        url,
        body: registrationInfo.toJson(),
      );

这个答案可能会进一步帮助您 - https://stackoverflow.com/questions/57846215/how-make-a-http-post-using-form-data-in-flutter

英文:

In postman screenshot you seem to be using form-data. You don't need to json encode your body.

final response = await post(
        url,
        body: registrationInfo.toJson(),
      );

This answer might help you further - https://stackoverflow.com/questions/57846215/how-make-a-http-post-using-form-data-in-flutter

huangapple
  • 本文由 发表于 2023年2月23日 19:16:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/75544079.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定