如何从在颤振中运行在本地主机上的服务器获取数据?

问题描述

我用 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)

解决方法

你必须先导入这个

import '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
  }
,

我不确定 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);
}