首页 > 解决方案 > 无法从 Flutter Web 上的 localhost API(node js express)获取 http 请求的响应

问题描述

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

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

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

如果我从(物理手机/失眠症/Chrome)访问但当我在本地主机上托管我的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/'));
      }

这个完全相同的代码非常适合移动应用程序或失眠症

失眠 poco x3 pro

网络选项卡开发工具

标签: node.jsflutterflutter-webflutter-http

解决方案


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

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

如果不工作:

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

如果它仍然不起作用,您可能会考虑使用代理或像ngrok这样的 http-tunnel


推荐阅读