【问题标题】:Unable to get response from http request from a localhost API (node js express) on Flutter Web [duplicate]无法从 Flutter Web 上的 localhost API(node js express)获取 http 请求的响应 [重复]
【发布时间】:2021-11-08 11:58:52
【问题描述】:

我构建了一个简单的 api,它的响应主体为 { "name": "saud", "age": "22" }

它使用 Node js express 托管在 http://localhost:7283/saud

app.get('/saud',(req,res)=>{res.status(200).send({name:'saud',age:'22'}) } );

如果我从 (实体手机/失眠症/Chrome) 访问,但当我在 localhost 上托管我的 Web 应用程序 并且请求被发送。 我不断收到 CircularProgressIndicator(意味着将来没有响应)

这是我的颤振代码:

    Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: SingleChildScrollView(
          child: FutureBuilder<http.Response>(
        future: getUrl(),
        builder: (context, snapshot) {
          if (snapshot.hasData) {
            print(json.decode(snapshot.data!.body));
            return Text(json.decode(snapshot.data!.body).toString());
          }
          return CircularProgressIndicator();
        },
      )),
    );
  }

Future<http.Response> getUrl() async {
        return http.get(Uri.parse('http://192.168.92.226:7283/saud/'));
      }

这个完全相同的代码非常适用于移动应用或失眠

insomnia poco x3 pro

network tab dev tools

【问题讨论】:

  • 能否请您在开发者工具的网络选项卡中显示请求?可能是 cors 问题或类似问题。
  • @jeremynac 在 OP 中附上了截图
  • @jeremynac 这是一个 cors 问题,左上角的红色按钮显示了这一点:从源 '192.168.92.226:7283/saud' 访问 XMLHttpRequest 已被 CORS 策略阻止:否'访问-Control-Allow-Origin' 标头出现在请求的资源上。

标签: node.js flutter flutter-web flutter-http


【解决方案1】:

“CORS 策略:无 'Access-Control-Allow-Origin'”错误意味着后端正在阻止您的前端请求,因为它在与后端端口不同的端口上的 http://localhost 上运行。 要修复它,只需在后端使用 cors 包:

app.use(cors({
    origin: '*'
}));

如果不工作:

app.use(cors({
    origin: 'http://localhost:<yourFlutterWebPort>'
}));

如果仍然无法正常工作,您可以考虑使用代理或 http 隧道,例如 ngrok

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-07-05
    • 2020-08-13
    • 1970-01-01
    • 1970-01-01
    • 2017-10-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多