I'm getting this message in debug console when I press my Register button
I/flutter (20697): SocketException: Connection refused (OS Error: Connection refused, errno = 111), address = localhost, port = 36192
How do I fix this?
CODE
Future save() async {
try {
var response = await http.post(Uri.parse("http://localhost:5000/user"),
headers: <String, String>{
'Context-Type': 'application/json;charSet=UTF-8'
},
body: <String, String>{
// 'role': user.role,
'name': user.name,
'email': user.email,
'phone': user.phone,
'password': user.password
});
if (response.statusCode == 200) {
var data = jsonDecode(response.body.toString());
print(data['token']);
print("account created succesfully");
} else {
print('failed');
}
} catch (e) {
print(e.toString());
}
}
This is the code, I use Uri.parse("http://localhost:5000/user") to connect. Also, I've tried already changing the localhost to my ipv4 and also 127.0.0.1 like that. But no change in result.
CodePudding user response:
You should use the machine's IP address where the API is running. Also, the API should listen to the IP 0.0.0.0
to be accessible outside the localhost.
It's going to be something like (suppose the API machine's IP is 192.168.1.123
):
Uri.parse("http://192.168.1.123:5000/user")
This happens because the localhost
(or 127.0.0.1
) on the device is only accessible to the device itself.
On the other hand, changing the API to listen to 0.0.0.0
is a security risk as the API is accessible to the outside world. So, if you're running an Android
device/emulator you can reverse-proxy a localhost port to the device/emulator running adb reverse
on the command prompt like so:
adb reverse tcp:5000 tcp:5000
This way, you can continue using the localhost:5000
in the device/emulator. There is no need to change it to the machine's IP.