无法向 python 本地服务器发送颤振 GET 请求

Posted

技术标签:

【中文标题】无法向 python 本地服务器发送颤振 GET 请求【英文标题】:Unable to send flutter GET request to python local server 【发布时间】:2021-06-05 14:33:17 【问题描述】:

我用 TextField() 和 Text() 小部件制作了一个简单的 Flutter Web 应用程序。当我按下按钮时,我希望它向使用 python 制作的简单烧瓶应用程序发送查询,它将返回反转的文本,并将其显示在 Text 小部件上。

注意:反转文本不是实际任务。它只是为了检查我是否 能够获取数据。

Python 代码:

当我在 chrome 上运行时,此代码有效。

#performing flask imports
from flask import Flask,jsonify
from flask.globals import request


app = Flask(__name__) #intance of our flask application 

#Route '/' to facilitate get request from our flutter app
@app.route("/api",methods=["GET"])
def function():
    d = 
    text = str(request.args["Query"])
    text = text[::-1]
    d["query"] = text
    return jsonify(d)

if __name__ == "__main__":
    app.run()

颤振代码:

main.dart

import 'package:flutter/material.dart';
import 'api.dart';
import 'dart:convert';

void main() => runApp(MyApp());

class MyApp extends StatefulWidget 
  @override
  _MyAppState createState() => _MyAppState();


class _MyAppState extends State<MyApp> 
  String url;

  var data;

  String queryText = "Query";

  @override
  Widget build(BuildContext context) 
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text("PYTHON AND FLUTTER"),
        ),
        body: Column(
          children: <Widget>[
            Padding(
              padding: const EdgeInsets.all(10.0),
              child: TextField(
                onChanged: (value) 
                  url = "http://10.0.2.2:5000/api?Query=" + value.toString();
                ,
                decoration: InputDecoration(
                    hintText: "Search Anything Here",
                    suffixIcon: GestureDetector(
                        onTap: () async 
                          data = await getData(url);
                          var decodedData = jsonDecode(data);
                          setState(() 
                            queryText = decodedData["Query"];
                          );
                        ,
                        child: Icon(Icons.search))),
              ),
            ),
            Padding(
              padding: const EdgeInsets.all(10.0),
              child: Text(
                queryText,
                style: TextStyle(fontSize: 30.0, fontWeight: FontWeight.bold),
              ),
            ),
          ],
        ),
      ),
    );
  

api.dart

import 'package:http/http.dart' as http;

Future getData(url) async 
  http.Response response = await http.get(url);
  return response.body;

我遵循了来自This Youtube Video的教程

我正在通过命令提示符运行 python 代码并通过 VScode 运行应用程序。

我收到以下错误:

Error: Expected a value of type 'Uri', but got one of type 'String'
    at Object.throw_ [as throw] (http://localhost:50523/dart_sdk.js:5348:11)
    at Object.castError (http://localhost:50523/dart_sdk.js:5319:15)
    at Object.cast [as as] (http://localhost:50523/dart_sdk.js:5635:17)
    at Function.as_C [as as] (http://localhost:50523/dart_sdk.js:5263:19)
    at getData (http://localhost:50523/packages/word_prediction/api.dart.lib.js:29:47)
    at getData.next (<anonymous>)
    at runBody (http://localhost:50523/dart_sdk.js:39211:34)
    at Object._async [as async] (http://localhost:50523/dart_sdk.js:39242:7)
    at Object.getData (http://localhost:50523/packages/word_prediction/api.dart.lib.js:28:18)
    at main._MyAppState.new.<anonymous> (http://localhost:50523/packages/word_prediction/main.dart.lib.js:422:48)
    at Generator.next (<anonymous>)
    at runBody (http://localhost:50523/dart_sdk.js:39211:34)
    at Object._async [as async] (http://localhost:50523/dart_sdk.js:39242:7)
    at http://localhost:50523/packages/word_prediction/main.dart.lib.js:421:210
    at tap.TapGestureRecognizer.new.invokeCallback (http://localhost:50523/packages/flutter/src/gestures/recognizer.dart.lib.js:203:18)
    at tap.TapGestureRecognizer.new.handleTapUp (http://localhost:50523/packages/flutter/src/gestures/tap.dart.lib.js:417:40)
    at tap.TapGestureRecognizer.new.[_checkUp] (http://localhost:50523/packages/flutter/src/gestures/tap.dart.lib.js:223:12)
    at tap.TapGestureRecognizer.new.acceptGesture (http://localhost:50523/packages/flutter/src/gestures/tap.dart.lib.js:199:23)
    at arena.GestureArenaManager.new.sweep (http://localhost:50523/packages/flutter/src/gestures/arena.dart.lib.js:222:31)
    at binding$5.WidgetsFlutterBinding.new.handleEvent (http://localhost:50523/packages/flutter/src/gestures/binding.dart.lib.js:402:27)
    at binding$5.WidgetsFlutterBinding.new.dispatchEvent (http://localhost:50523/packages/flutter/src/gestures/binding.dart.lib.js:381:24)
    at binding$5.WidgetsFlutterBinding.new.dispatchEvent (http://localhost:50523/packages/flutter/src/rendering/layer.dart.lib.js:6107:13)
    at binding$5.WidgetsFlutterBinding.new.[_handlePointerEventImmediately] (http://localhost:50523/packages/flutter/src/gestures/binding.dart.lib.js:352:14)
    at binding$5.WidgetsFlutterBinding.new.handlePointerEvent (http://localhost:50523/packages/flutter/src/gestures/binding.dart.lib.js:325:43)
    at binding$5.WidgetsFlutterBinding.new.[_flushPointerEventQueue] (http://localhost:50523/packages/flutter/src/gestures/binding.dart.lib.js:314:14)
    at binding$5.WidgetsFlutterBinding.new.[_handlePointerDataPacket] (http://localhost:50523/packages/flutter/src/gestures/binding.dart.lib.js:304:65)
    at Object.invoke1 (http://localhost:50523/dart_sdk.js:185426:7)
    at _engine.EnginePlatformDispatcher.__.invokeOnPointerDataPacket (http://localhost:50523/dart_sdk.js:165747:15)
    at _engine.PointerBinding.__.[_onPointerData] (http://localhost:50523/dart_sdk.js:166405:49)
    at http://localhost:50523/dart_sdk.js:166863:28
    at http://localhost:50523/dart_sdk.js:166816:16
    at http://localhost:50523/dart_sdk.js:166509:11

我不知道我在这里做错了什么。

【问题讨论】:

【参考方案1】:

试试这个:

Future getData(String url) async 
  var response = await http.get(Uri.parse(url));
  return response.body;

【讨论】:

我没有收到上述错误,但代码也不起作用。我按了 2-3 次按钮,但什么也没发生,并且在第 69 行(completer.completeError)的 browser_client.dart 中突然停止执行。 您是否尝试在终端中运行您的 API 请求?在 Linux 中你可以使用:curl -X GET "http://10.0.2.2:5000/api?Query=my_value" 这样你可以检查你的服务器是否工作正常 这很奇怪,因为您的错误清楚地表明错误是关于缺少 Uri。在 Dart 中创建一个简单的脚本,只请求特定的 url,检查错误是否仍然存在。 您提供的解决方案是正确的。但与此同时,需要对服务器端代码进行一些更改才能完全完成这项工作。【参考方案2】:

随着这个变化https://***.com/a/66517561/13592012 Ουιλιαμ Αρκευα 提到。

还有一个问题: 当我使用 Break point 时,它会显示通过blinding.dart 调用的文件

这是因为 CORS。

Cross Origin Request(CORS) 错误,这是因为我没有在我的服务器中设置它。

如果您的 Flutter Web 应用程序与您运行 api 的服务器不在同一个域中运行,则尤其如此。即使它在同一台机器上,您也必须允许来自某些域和端口的请求。

这可以通过在烧瓶代码中添加以下行来完成:

response.headers.add("Access-Control-Allow-Origin", "*")

response.headers.add("Access-Control-Allow-Credentials", "true")

所以更新后的代码是:

#performing flask imports
from flask import Flask,jsonify
from flask.globals import request


app = Flask(__name__) #intance of our flask application 

#Route '/' to facilitate get request from our flutter app
@app.route("/api",methods=["GET"])
def word_predictor():
    d = 
    text = str(request.args["Query"])
    text = text[::-1]
    d["Query"] = text
    response = jsonify(d)
    response.headers.add("Access-Control-Allow-Origin", "*")
    response.headers.add("Access-Control-Allow-Credentials", "true")
    return response

if __name__ == "__main__":
    app.run()

而且,通过这两项更改,代码可以正常工作。

【讨论】:

以上是关于无法向 python 本地服务器发送颤振 GET 请求的主要内容,如果未能解决你的问题,请参考以下文章

尝试向 Flutter 发送平台消息,但 FlutterJNI 与原生 C++ 分离。无法发送。频道:颤振/文本输入。响应 ID:0

本地html向远程的服务器发送aJax请求的问题

从后台颤振隔离向Android方法发送平台消息

无法从服务器向 FCM url 发送请求(相同的代码在本地 pc 上工作)

如何从flutter应用程序向本地主机发出http get请求?

有啥办法可以防止颤振向谷歌发送崩溃报告