【问题标题】:Python Flask not returning Post data to ReactPython Flask 没有将 Post 数据返回给 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 解决了问题,谢谢!

标签: javascript fetch-api


【解决方案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 文档:fetchUsing 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
<script>
async function test() {
    await fetch('/data', {
                  method: 'POST',
                  //credentials: 'include',
                  headers: {'Content-Type': 'application/json'},
                  body: JSON.stringify('message'),
                })
                .then(response => response.text())
                .then(text => {console.log('The response was....', text);});
                //.then(response => response.json())
                //.then(data => {console.log('The response was....', data['hello']);});
}

test();
</script>
''')

@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()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-06-11
    • 2018-05-16
    • 2017-05-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多