не удается получить данные от flutter в nodejs

#node.js #flutter #node-oracledb

Вопрос:

Я пытаюсь войти в систему с помощью Flutter, Nodejs(Express) и oracle бэкэнд работает, когда я тестирую его с ПОЧТАЛЬОНОМ, я могу получить токен здесьвведите описание изображения здесь, данные теста почтальона отображаются в cmd, когда я пытаюсь с почтальоном введите описание изображения здесь

это изображение содержит данные, отображаемые в отладчике flutter

введите описание изображения здесь но проблема в том, что когда я пытаюсь связать флаттер и узел, данные, отправленные из флаттера, не принимаются в узле js IDNUMBER и PASS имеют значение неопределенных средств req.body.IDNUMBER=undefined , а req.body.PASS=undefined данные отображаются в cmd, когда я пытаюсь использовать флаттер в узлах

введите описание изображения здесь

Я знаю, что мне чего-то не хватает

вот код флаттера

 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)
  } 
}) 

Ответ №1:

  • Используйте jsonEncode для отправки своих параметров.
  • Используйте заголовки, чтобы сообщить вашему серверу 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);
 

Комментарии:

1. у тебя какая-то проблема, друг

2. это ошибка, которую я получаю в nodejs Cannot read property '0' of undefined

3. что означает этот журнал ` console.log( the req id ${req.body.IDNUMBER} )`?

4. Я просто использую его, чтобы проверить req.body.IDNUMBER значение, которое я получаю в бэкэнде, если оно не определено, то я не получаю данные от flutter

5. ЧТО ОН ПЕЧАТАЕТ?