Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting error message with random port while making request to localhost from Flutter app

Tags:

flutter

dart

** update ** Fixed it by editing my server to listen on 0.0.0.0 Getting a response now, but still, the error message wasn't right, it should've shown port 3333 not a random port. --- // ---

While trying to make a post request to http://192.168.1.1:3333, I get this error:

SocketException (SocketException: OS Error: Connection timed out, errno = 110, address = 192.168.2.9, port = 53744)

The port changes on every request but is never the right port (3333) why is that? This is my code

class Api {
  static const req_url = 'http://192.168.1.1:3333/api/auth/login';

  Future<Auth> fetchAuthToken() async {

    Map data = {
      'email': '[email protected]',
      'password': '123456'
    };

    //encode Map to JSON
    var body = json.encode(data);

    var response = await http.post(req_url,
        headers: {"Content-Type": "application/json"},
        body: body
    );
    if (response.statusCode == 200) {
      // If the call to the server was successful, parse the JSON
      return Auth.fromJson(json.decode(response.body));
    } else {
      // If that call was not successful, throw an error.
      throw Exception('Failed to load post');
    }
  }
}

I've tried changing the ip to 10.0.2.2 as mentioned here but I'm not using an emulator so not sure if that even matters.

like image 375
Karl Avatar asked Dec 29 '25 11:12

Karl


1 Answers

I had the same issue with my Flutter app running express.js server, but had it fixed by letting my expresss server listen on 0.0.0.0 port 3333, and within my flutter app i changed my post url to my mac IP on the network with same port 3333 http://192.168.43.210:3333/api/v02 , and boom the emulator worked

void _mypost() {

    Map<String,String> data = {
              'token':'2jmj7l5rSw0yVb/vlWAYkK/YBwk=',
              'phone':'+256750002991',
           };
    Map<String,String> headers ={
            'Content-Type': 'application/x-www-form-urlencoded'
    };
    var client = httpClient.Client();
    client.post("http://192.168.43.210:3333/api/v02", headers:headers, body:data)
    .then((response) => print(" Response Body ${response.body}"))
    .catchError((error) => print(" Response Body : ${error}"));
}
like image 59
user1623814 Avatar answered Dec 31 '25 09:12

user1623814