Python Flask 没有将 Post 数据返回给 React

分享于2022年07月17日 fetch-api javascript 问答
【问题标题】:Python Flask 没有将 Post 数据返回给 React(Python Flask not returning Post data to React)
【发布时间】:2022-01-26 00:44:24
【问题描述】:

我在让我的烧瓶后端向我的 REACT js 前端发送响应时遇到问题。以下是在 REACT js 前端中使用的代码创建一个发送字符串“消息”的发布请求。然后烧瓶后端应该将字符串发回,并且将创建一个显示字符串的控制台日志。

反应 JS

        const response2 = await fetch(`${process.env.REACT_APP_TEST}`,{
            method: 'POST',
            credentials: 'include',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify('message'),
        }
        )
        
        console.log('The response was....', response2)

烧瓶

@app.route("/", methods=['GET', 'POST'])
@cross_origin(supports_credentials=True)
def index():
    print('Running')
    print 
    sent_data = request.get_json()
    print(sent_data)
    if sent_data != 'message':
        return ({"hello": ['no']})
    else:
        return (sent_data)

在后端获取数据并打印“消息”,以便信息到达烧瓶。 问题是我没有收到在 React js 控制台中记录的字符串“消息”...

The response was.. {type: "cors", url: "http://127.0.0.1:5000/", redirected: false, status: 200, ok: true, statusText: "OK", headers: Headers, body: ReadableStream, bodyUsed: false}

如果有任何不清楚的地方,请告诉我并感谢您的帮助,谢谢!

  • 我认为你使用 fetch 的方式是扭曲的。它不会从服务器返回 response ,而只会返回它发送数据的信息——对象 Promise 。您应该使用 fetch().then(...) requests = await fetch() requests.then(...) 就像在文档中一样 Using_Fetch
  • 您可能需要使用 return jsonify(send_data) 并在反应 response2 = response2.then(resp => resp.json())
  • @furas 解决了问题,谢谢!

【解决方案1】:

从未使用过 React,但我认为您以错误的方式使用 fetch

它可能会给出 Promise 而不是 response ,你应该使用

fetch(...)
.then( response => response.text() )
.then( text => {console.log('The response was....', text);} );

或者,如果您使用 return jsonify(send_data) 而不是 return send_data ,那么您将需要 resonse.json() 而不是 response.text()
然后你会得到 data["hello"] ,如果它会发送 {"hello": ['no']}

fetch(...)
.then( response => response.json() )
.then( data => {console.log('The response was....', data);} );

Mozilla 文档: fetch Using Fetch


最小的工作示例:

from flask import Flask, request, render_template_string, jsonify

app = Flask(__name__)

@app.route('/', methods=['GET', 'POST'])
def index():
    return render_template_string('''
TEST

''')

@app.route("/data", methods=['GET', 'POST'])
#@cross_origin(supports_credentials=True)
def data():
    print('running: /data')
    
    data = request.get_json()
    print('data:', data)
    
    if data != 'message':
        return jsonify({'hello': ['no']})
    else:
        return jsonify(data)

if __name__ == '__main__':
    #app.debug = True 
    app.run()