简体   繁体   English

Python Flask 不返回 Post 数据到 React

[英]Python Flask not returning Post data to React

I am having a problem with getting my flask backend to send a response back to my REACT js frontend.我在让我的 flask 后端向我的 REACT js 前端发送响应时遇到问题。 The following is the code used in REACT js frontend create a post request sending the string, 'message'.以下是在 REACT js 前端中使用的代码创建一个发送字符串“消息”的发布请求。 The flask backend should then send the string back and a console log will be created displaying the string.然后 flask 后端应该将字符串发回,并且将创建一个显示字符串的控制台日志。

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)

Flask Flask

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

The data is picked up on the backend and prints "message" so information is getting to flask.数据在后端被提取并打印“消息”,因此信息正在到达 flask。 The issue is that instead of receiving the string 'message' logged in the React js console I get...问题是,我没有收到在 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}

If anything is unclear let me know and appreciate the help, thanks!如果有任何不清楚的地方,请告诉我并感谢您的帮助,谢谢!

Never worked with React but I think you use fetch in wrong way.从未使用过 React,但我认为您以错误的方式使用fetch

It may give Promise instead of response and you should rather use它可能会给出Promise而不是response ,您应该使用

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

Or if you would use return jsonify(send_data) instead of return send_data then you would need resonse.json() instead of response.text() .或者,如果您使用return jsonify(send_data)而不是return send_data那么您将需要resonse.json()而不是response.text()
And then you would get data["hello"] if it would send {"hello": ['no']}然后你会得到data["hello"]如果它会发送{"hello": ['no']}

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

Mozilla doc: fetch and Using Fetch Mozilla 文档:获取使用 Fetch


Minimal working example:最小的工作示例:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM