如何将Flutter应用连接到本地Node.js+MongoDB后端?
Flutter连接本地Node.js后端的配置问题解决
问题场景
- 本地运行Node.js + MongoDB后端,MongoDB配置如下:
const MONGO_DB_CONFIG = { DB: "mongodb://localhost/ecommerce-app" }
- 通过Postman可正常访问后端API:
http://localhost:4000/api/products/ - Flutter应用中配置了API地址:
class Config { static const String apiURL = "10.0.2.2:4000"; }
- 运行Flutter应用时出现连接拒绝错误:
Performing hot restart... Syncing files to device sdk gphone64 x86 64... Restarted application in 2,077ms. I/.mongo_database(18019): NativeAlloc concurrent copying GC freed 56675(1921KB) AllocSpace objects, 0(0B) LOS objects, 49% free, 2514KB/5029KB, paused 544us,73us total 273.631ms ======== Exception caught by image resource service ================================================ The following SocketException was thrown resolving an image codec: Connection refused (OS Error: Connection refused, errno = 111), address = localhost, port = 38912
解决方案
1. 补全API URL的协议头
Flutter的API地址必须包含协议(http://),否则请求会解析错误,修改Config类:
class Config { static const String apiURL = "http://10.0.2.2:4000"; }
2. 确保Node后端监听所有网络接口
如果Node后端仅绑定localhost(127.0.0.1),Android模拟器无法通过10.0.2.2访问。修改后端启动代码,让服务监听0.0.0.0:
// 替换原启动代码 app.listen(4000, '0.0.0.0', () => { console.log('Server running on http://0.0.0.0:4000'); });
3. 检查Flutter请求代码的地址引用
错误日志显示请求目标是localhost,说明代码中可能有硬编码的localhost地址未替换。确保所有API请求都使用Config中的地址:
// 正确的请求写法 final response = await http.get(Uri.parse('${Config.apiURL}/api/products'));
4. 验证端口与防火墙设置
- 确认本地4000端口未被其他程序占用:Windows用
netstat -ano | findstr :4000,Mac/Linux用lsof -i :4000。 - 关闭本地防火墙或添加4000端口的入站规则,允许模拟器访问。
5. 不同设备的适配配置
- iOS模拟器:直接使用
localhost即可,无需替换为10.0.2.2。 - 物理设备:将API地址改为本地电脑的局域网IP(如
http://192.168.1.100:4000),且设备与电脑需在同一局域网下。
内容的提问来源于stack exchange,提问作者pomoworko.com
相关产品推荐
相关产品推荐

