node.js - 无法从 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/'));
}
这个完全相同的代码非常适合移动应用程序或失眠症
解决方案
“CORS policy: No 'Access-Control-Allow-Origin'”错误意味着后端正在阻止您的前端请求,因为它在与后端端口不同的端口上的 http://localhost 上运行。要修复它,只需在后端使用 cors 包:
app.use(cors({
origin: '*'
}));
如果不工作:
app.use(cors({
origin: 'http://localhost:<yourFlutterWebPort>'
}));
如果它仍然不起作用,您可能会考虑使用代理或像ngrok这样的 http-tunnel
推荐阅读
- python - AWS how do read params for a POST with binary payload?
- excel - Transferring DAX formulas from Powerbi to Power Pivot in Excel
- c# - With Microsoft.Extensions.DependencyInjection, can I resolve the type and construct an instance while providing extra constructor parameters?
- c# - Unity, C# - pointer using mouse
- python - Nested FOR loop for my web scraper halfway working (Beautiful Soup)
- reactjs - React window how to iterate your data?
- powershell - In these Powershell -replace commands from the cmd prompt, why does the first escape double quotes successfully and the second doesn't?
- javascript - HCL Notes 11 - Javascript - context.text not working in firefox but works in IE
- asynchronous - Why is there not a "cursor" for caller to async_send_some with ConstBufferSequence buffers?
- c# - 如何将用户重定向到登录页面以及成功登录后如何在C#中捕获令牌