【问题标题】:How to fetch data from a server running on localhost in flutter?如何从在 localhost 上运行的服务器获取数据?
【发布时间】:2021-05-04 03:57:47
【问题描述】:

我在 python 中编写了一个 API,并在 http://127.0.0.1:5000 上运行它。 (使用 Flask。另外,我目前正在开发服务器上运行它以进行测试)

但是当我尝试在 Flutter 中使用 http 包获取响应时,我得到了一个 XMLHttpRequest 错误。

void api() async {
  const String url = "http://127.0.0.1:5000/dosomething?query=This doesn't work!"; # this is an example
  Response response = await get(url);
  print(response.body); # I'm printing this for testing
}

注意:我也检查了 URL,它有效。

可能是什么问题?以及如何解决?

重要提示 - 当我尝试使用在网络上运行的 API(在本例中为 WorldTimeAPI)时,以下答案有效。但是,当我尝试使用我的代码时,它以某种方式不起作用。虽然当我手动测试它时它工作得很好。

这是我的 API 代码的简化版本 -

from flask import Flask, request, jsonify

app = Flask(__name__)

@app.route('/dosomething', methods = ['GET'])
def API():
     result = {}
     result['result'] = user_input = str(request.args['query'])
     return jsonify(result)

【问题讨论】:

  • Future替换void()然后试试

标签: python api flutter localhost


【解决方案1】:

你必须先导入这个

将'package:http/http.dart'导入为http;

然后对于 API 调用,传递您的 HTTP 扩展名,然后传递您的身体类型,例如 post or get

  Future api() async {
    const String url = 'http://127.0.0.1:5000/dosomething?query=This doesn't work!';
    Response response = await http.get(url);  // here i passed http.get
    print(response.body); // You should get your result
  }

【讨论】:

  • 是的,我检查完了。当我使用实际的 API(在本例中为 WorldTimeAPI)进行检查时,它可以工作。但是当我尝试使用自己的 API(在 localhost 上运行)时,它不起作用。 API会不会有问题? (虽然我手动尝试时效果很好)
  • @AnshulRaj 不确定,关于您的 API,您的 API 或数据中可能存在问题
  • 我也对此表示怀疑,但是如果API有问题,那么为什么我将它粘贴到Chrome中时它会起作用?使用 localhost 有问题吗?我应该以某种方式在网络上设置它然后尝试吗?
  • 我绑了邮递员。有用。但是为什么我不能直接做呢?
【解决方案2】:

我不确定 get 函数是做什么的,但是像这样使用 http:

import 'package:http/http.dart' as http; //Import in the beginning of file

void api() async {
  const String url = 'http://127.0.0.1:5000/dosomething?query=This doesn't work!';
  var response = await http.get(url);
  print(response.body);
}

【讨论】:

  • 我已经检查了代码。当我使用实际的 API(在本例中为 WorldTimeAPI)进行检查时,它可以工作。但是当我尝试使用自己的 API(在 localhost 上运行)时,它不起作用。 API会不会有问题? (虽然我手动尝试时效果很好)
  • 究竟是什么不起作用?也许你可以把 API 代码发给你。
  • 你可以在这里查看我的代码-drive.google.com/drive/folders/…希望你能帮忙,谢谢
  • 你能告诉我到底是什么不工作吗?是抛出什么错误还是什么?
  • API 似乎工作正常。 HTTP 请求也是如此。但不知何故,它无法获取 API 响应。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-02-18
  • 2012-12-02
  • 2019-04-20
  • 1970-01-01
  • 2022-06-16
  • 2018-09-04
  • 1970-01-01
相关资源
最近更新 更多