无法从 flutter 接收数据到 nodejs

can't receive data from flutter to nodejs

我尝试使用 Flutter、Nodejs(Express) 和 oracle 进行登录 当我用 POSTMAN 测试它时,后端正在工作,我可以获得令牌 这里 postman test 当我尝试使用 Postman 时,数据显示在 cmd 中

此图像包含 flutter 调试器中显示的数据

但问题是 当我尝试 link flutter 和节点时,节点 js 没有收到从 flutter 发送的数据 IDNUMBERPASS 的值为 undefined 表示 req.body.IDNUMBER=undefinedreq.body.PASS=undefined 当我尝试在 nodejs 中使用 flutter 时,cmd 中显示的数据

我知道我错过了什么

这里是 flutter 代码

import 'dart:convert';

import 'package:app_project/homepage.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:shared_preferences/shared_preferences.dart';

class Login extends StatefulWidget {
  Login({Key? key}) : super(key: key);

  @override
  _LoginState createState() => _LoginState();
}

class _LoginState extends State<Login> {
  TextEditingController _idNumberController = new TextEditingController();
  TextEditingController _passController = new TextEditingController();
  bool _isloading = false;
  bool showpass = true;
  String url = "http://192.168.1.19:3000/auth2";
  signIn(String idNumber, String pass) async {
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    Map body = {"IDNUMBER": idNumber, "PASS": pass};
    var jsonResponse;
    var res = await http
        .post(Uri.parse(url), body: {"IDNUMBER": idNumber, "PASS": pass});
    // check the api status (connection)
    if (res.statusCode == 200) {
      jsonResponse = await json.decode(json.encode(res.body));
      print("the body is ${body}");
      print("Response  status 1 :${res.statusCode}");
      print("Response  status 2 :${res.body}");

      if (jsonResponse != null) {
        setState(() {
          _isloading = false;
          print("Response  status 2 2 :${res.body}");
        });
        //print(jsonResponse.runtimeType);
        sharedPreferences.setString("token", jsonResponse.toString());
        Navigator.of(context).pushReplacementNamed("homepage");
      }
    } else {
      setState(() {
        _isloading = false;
      });
      print("Response  status 3 :${res.body}");
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: ListView(
        children: [
          Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Image.asset("images/1.png"),
              Container(
                margin: EdgeInsets.all(20),
                child: Form(
                    child: Column(
                  children: [
                    TextFormField(
                      controller: _idNumberController,
                      cursorColor: Colors.red,
                      style: TextStyle(fontSize: 20),
                      decoration: InputDecoration(
                          hintText: "اكتم رقمك التسلسلي",
                          prefixIcon: Icon(Icons.person),
                          filled: true,
                          fillColor: Colors.orange[100],
                          focusedBorder: OutlineInputBorder(
                              borderRadius: BorderRadius.circular(100),
                              borderSide:
                                  BorderSide(color: Colors.orange, width: 3)),
                          border: OutlineInputBorder(
                              borderRadius: BorderRadius.circular(100),
                              borderSide:
                                  BorderSide(width: 1, color: Colors.orange)),
                          focusColor: Colors.red),
                    ),
                    SizedBox(
                      height: 30,
                    ),
                    TextFormField(
                      controller: _passController,
                      cursorColor: Colors.red,
                      obscureText: showpass,
                      style: TextStyle(fontSize: 20),
                      decoration: InputDecoration(
                          suffixIcon: IconButton(
                              onPressed: () {
                                setState(() {
                                  showpass = !showpass;
                                });
                              },
                              icon: showpass
                                  ? Icon(Icons.remove_red_eye_sharp)
                                  : Icon(Icons.remove_red_eye_outlined)),
                          hintText: "اكتم كلمة المرور",
                          prefixIcon: Icon(Icons.lock),
                          filled: true,
                          fillColor: Colors.orange[100],
                          focusedBorder: OutlineInputBorder(
                              borderRadius: BorderRadius.circular(100),
                              borderSide:
                                  BorderSide(color: Colors.orange, width: 3)),
                          border: OutlineInputBorder(
                              borderRadius: BorderRadius.circular(100),
                              borderSide:
                                  BorderSide(width: 1, color: Colors.orange)),
                          focusColor: Colors.red),
                    ),
                    SizedBox(
                      height: 30,
                    ),
                    ElevatedButton.icon(
                        style: ElevatedButton.styleFrom(
                            padding: EdgeInsets.symmetric(
                                horizontal: 35, vertical: 15),
                            shape: RoundedRectangleBorder(
                                borderRadius: BorderRadius.circular(100))),
                        onPressed: () {
                          setState(() {
                            _isloading = true;
                          });
                          signIn(
                              _idNumberController.text, _passController.text);
                          print("id = ${_idNumberController.text}");
                          print("pass = ${_passController.text}");
                        },
                        icon: Icon(Icons.login),
                        label: Text("سجل الدخول"))
                  ],
                )),
              )
            ],
          )
        ],
      ),
    );
  }
}

这里是节点代码post函数

app.post("/auth2", async (req, res) => {
  try {
    connection = await oracledb.getConnection({
      user: "system",
      password: password,
      connectString: "localhost:1521/XE"
    });

    console.log('connected to database');
    // run query to get all employees
     console.log(`the req id ${req.body.IDNUMBER}`)
     console.log(`the req PASS ${req.body.PASS}`)
result = await connection.execute(`SELECT IDNUMBER,PASS FROM USERS WHERE IDNUMBER=:IDNUMBER AND PASS=:PASS`,
    [req.body.IDNUMBER,req.body.PASS]
     );
    let ress = {
      "IDNUMBER": result.rows[0][0],
        "PASS":result.rows[0][1]  
    }
    
    console.log({
    //those variables show as undefined
      "IDNUMBER": result.rows[0][0], 
       "PASS":result.rows[0][1]  
    })
    if (result.rows.length != 0) {
      const token = jwt.sign({ _id: ress }, 'privateKey');
      console.log(token);
      res.json({ token: token });
    } else {
      res.json({"message":"there is no one in the database has this idnumber"})
    }
    
  } catch (err) {
    console.log("the information is not passing ")
    return res.send(err.message)
  } 
})

  • 使用 jsonEncode 发送您的参数。
  • 使用 headers 告诉您的 NodeJs 服务器您正在发送参数。
Map<String, String> requestHeaders = 
{'Content-type': 'application/json',
'Accept': 'application/json',}; 

var res = await http.post(Uri.parse(url),body:jsonEncode(body), headers: requestHeaders);