You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter无法连接Node.js本地localhost:3000服务器求助

解决Flutter Dio请求本地Node.js服务器超时问题

问题情况

Flutter中通过按钮触发getTest方法,使用Dio请求本地Node.js服务器(localhost:3000)的/test接口,点击按钮后出现连接超时错误,服务器端无任何日志输出。

相关代码

Flutter按钮触发方法代码

void getTest() async {
  BaseOptions options = BaseOptions(
    baseUrl: "http://10.0.2.2:3000",
    // connectTimeout: 1000,
    // receiveTimeout: 3000,
  );
  Dio dio = Dio(options);
  try {
    Response resp = await dio.post(
      options.baseUrl + "/test",
    );
  } catch (e) {
    print("Exception: $e");
  }
}

Node.js服务器代码

const express = require('express');
const { Server } = require('ws');

const app = express();

app.get("/test", function(req, res){
  
  console.log(req)
});

app.post("/test", function(req, res){
  
  console.log(req)
});

app.listen(3000, function() {
  console.log("Server started on port 3000");
});

Debug控制台错误信息

Exception: DioError [DioErrorType.connectTimeout]: Connecting timed out [0ms]

排查与解决方案

  • 确认Node服务器状态:检查服务器控制台是否输出Server started on port 3000,用Postman或浏览器发送POST请求到http://localhost:3000/test,验证服务器是否能接收请求并打印日志。如果服务器无响应,检查端口是否被占用,尝试更换端口(如3001)重启服务器。

  • 添加Android网络权限:在Android项目的android/app/src/main/AndroidManifest.xml中,<manifest>标签内添加网络权限配置:

    <uses-permission android:name="android.permission.INTERNET" />
    
  • 修正Flutter请求地址:简化请求路径写法,直接使用相对路径避免重复拼接baseUrl:

    Response resp = await dio.post("/test");
    
  • 适配不同模拟器地址:

    • Android模拟器使用http://10.0.2.2:3000映射本地localhost;
    • iOS模拟器直接使用http://localhost:3000即可。
  • 检查防火墙设置:关闭电脑防火墙,确认3000端口未被拦截。

  • 完善Node服务器响应逻辑:当前POST路由仅打印请求对象但未返回响应,添加响应语句避免请求挂起:

    app.post("/test", function(req, res){
      console.log(req)
      res.send("Received POST request"); // 添加响应
    });
    

内容的提问来源于stack exchange,提问作者nishant patil

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 16:16:05