0

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!

3
  • I think you use fetch in wring way. It doesn't return response from server but only information where it send data - object Promise. You should use rather fetch().then(...) or requests = await fetch() and requests.then(...) like in doc Using_Fetch Commented Dec 26, 2021 at 21:59
  • you may need to use return jsonify(send_data) and in react response2 = response2.then(resp => resp.json()) Commented Dec 26, 2021 at 22:16
  • @furas that's solved the problem, thanks! Commented Dec 27, 2021 at 8:51

2 Answers 2

1

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()
Sign up to request clarification or add additional context in comments.

Comments

0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.