0

i wanna connect my backend and frontend. but i dont understand flutter code to POST api code. so i dont know what is the problem backend and frontend. i need your help.

import "./db";
import "./models/Todo";
import express from "express";

const app = express();
const PORT = 3000;

const handleHome = (req, res) => {
  return res.send("Welcome to my Home");
};

const postTodo = async (req, res) => {
  const { title, description } = req.body;
  await Todo.create({
    title,
    description,
  });
  return res.end();
};

app.post("/todo", postTodo);

app.get("/", handleHome);

const handleListening = () => {
  console.log(`✅Server listening on port : http://localhost:${PORT} `);
};

app.listen(PORT, handleListening);

that is nodeJS code for server. i wanna get todo by '/todo' that is correct? i use mongodb for database

import mongoose from "mongoose";

const todoSchema = new mongoose.Schema({
  title: String,
  description: String,
});

const Todo = mongoose.model("Todo", todoSchema);
export default Todo;

this is todo model. for mongodb

import 'dart:convert';
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

Future<Todo> createTodo(String title,String description) async{
  final response = await http.post(
    Uri.parse('http://localhost:3000/todo'),
    headers: <String, String>{
    'Content-Type': 'application/json; charset=UTF-8',
  },
    body: jsonEncode(<String, String>{
      'title':title,
      'description' :description,
    }),
  );
  print(response.body);
  if(response.statusCode == 201){
    return Todo.fromJson(jsonDecode(response.body));
  }else{
    throw Exception('Failed to create user');
  }
}

class Todo{
  final String title,description;

  Todo.fromJson(Map<String, dynamic> json):
    title= json['title'],
    description= json['description'];
}

class HomeScreen extends StatelessWidget {
  HomeScreen({super.key});
  TextEditingController _todoController = TextEditingController();
  TextEditingController _desController = TextEditingController();
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        body: SafeArea(
          child: Padding(
            padding: const EdgeInsets.symmetric(horizontal:20),
            child: Column(
              children: [
                SizedBox(height:60),
                TextFormField(
                  controller:_todoController,
                  decoration:InputDecoration(
                    hintText:'todo',
                    border: OutlineInputBorder(
                      borderSide: BorderSide(
                        color: Colors.black,
                        width: 3
                      )
                    )
                  ),
                ),
                TextFormField(
                  controller:_desController,
                  decoration:InputDecoration(
                    hintText:'todo',
                    border: OutlineInputBorder(
                      borderSide: BorderSide(
                        color: Colors.black,
                        width: 3
                      )
                    )
                  ),
                ),
                ElevatedButton(
                  child: Icon(Icons.arrow_right),
                  onPressed: () {
                    var newTodo = createTodo(_todoController.text,_desController.text);
                    print(newTodo);
                  },
                )
              ],
            ),
          ),
        ),
      ),
    );
  }
}

this is flutter code. how can i post data in flutter?? that code is correct?

how can i connect this code? i need your help please helpme

error is

flutter: Instance of 'Future<Todo>'
[VERBOSE-2:dart_vm_initializer.cc(41)] Unhandled Exception: Connection refused
#0      IOClient.send (package:http/src/io_client.dart:88:7)
<asynchronous suspension>
#1      BaseClient._sendUnstreamed (package:http/src/base_client.dart:93:32)
<asynchronous suspension>
#2      _withClient (package:http/http.dart:164:12)
<asynchronous suspension>
#3      createTodo (package:login_app/home_screen.dart:7:20)
<asynchronous suspension>
kim
  • 31
  • 2
  • Hi, did you test your nodejs api without flutter, with a tool like curl or postman ? From your error message Connection refused. It usually seems related to emulator not knowing about localhost, you have to provide an ip adress. you can look at [this](https://stackoverflow.com/questions/55785581/socketexception-os-error-connection-refused-errno-111-in-flutter-using-djan) post or [here](https://www.fluttercampus.com/guide/234/connection-refused-error-localhost/) – Loulou BadWeed Jan 07 '23 at 13:39

0 Answers0