Flutter 没有收到来自 Flask rest API 的响应

问题描述

我正在构建一个带有 Flutter 的移动应用程序,并与我使用 Flask 构建的一个 rest API 进行通信。不过,我对这两种技术还是陌生的。当我用邮递员测试时一切正常,但是当我从我的 Flutter 应用程序测试时,请求实际上处理并在我的 Flask 应用程序中记录状态代码 200,但响应不知何故没有返回或格式不正确,因为 Flutter 总是显示错误而是说:XMLHttpRequest error 而不是 json 响应。

飞镖代码

final String url = 'http://127.0.0.1:5000/endpoint';
http.Response response = await http.post(url,body: json.encode(body)); 
print(json.decode(response.body));

烧瓶代码

@app.route('/endpoint',methods=['POST'])
def save_point():
    try:
        body = utils.bytes_to_dict(request.get_data())
        assets = body.get('assets',[])
        if len(assets) < 1:
            raise Exception("'assets' is required")
        
        admin.insert(data = {'selected_assets': assets,'created_at': utils.gettime()},id = 'selected_assets')


        return jsonify({ # response is returned here
            'status': True,'message': 'Selected assets saved','data': assets
        })
    except Exception as e:
        print('error',e)
        return {
            'status': False,'message': str(e)
        }

我已经尝试通过以下方式在颤振中向请求添加 content-type 标头: await http.post(url,body: json.encode(body),headers: {'Content-type': 'application/json'}); 但这会导致请求无法在 Flask 中处理,原因我不知道。

请问有什么问题吗?有没有办法让颤振来理解响应?

解决方法

我必须在我的帖子请求中添加标题:{"Content-Type": "application/json"}。

,

我认为错误在这一行:

body: json.encode(body)

'body'的格式已经是JSON了,这行又要编码了