gah19
gah19

Reputation: 11

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. The following is the code used in REACT js frontend create a post request sending the string, 'message'. The flask backend should then send the string back and a console log will be created displaying the string.

REACT 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

@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. The issue is that instead of receiving the string 'message' logged in the React js console I get...

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!

Upvotes: 0

Views: 2413

Answers (2)

DanteDX
DanteDX

Reputation: 1259

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

console.log('The response was....', response2)

Upvotes: 0

furas
furas

Reputation: 142641

Never worked with React but I think you use fetch in wrong way.

It may give Promise instead of response and you should rather use

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().
And then you would get data["hello"] if it would send {"hello": ['no']}

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

Mozilla doc: fetch and Using 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()

Upvotes: 1

Related Questions