Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

149
Views
Python Flask no devuelve datos de publicación a React

Tengo un problema para hacer que el backend de mi matraz envíe una respuesta a mi frontend REACT js. El siguiente es el código utilizado en la interfaz REACT js para crear una solicitud de publicación que envíe la cadena 'mensaje'. El backend del matraz debe devolver la cadena y se creará un registro de la consola que muestra la cadena.

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

Matraz

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

Los datos se recogen en el backend e imprimen un "mensaje" para que la información llegue al matraz. El problema es que, en lugar de recibir la cadena 'mensaje' registrada en la consola React js, obtengo...

 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}

Si algo no está claro, hágamelo saber y agradezco la ayuda, ¡gracias!

about 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Nunca trabajé con React pero creo que usas fetch de manera incorrecta.

Puede dar Promise en lugar de response y debería usar más bien

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

O si usaría return jsonify(send_data) en lugar de return send_data , entonces necesitaría resonse.json() en lugar de response.text() .
Y luego obtendría data["hello"] si enviara {"hello": ['no']}

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

Mozilla doc: buscar y usar Fetch


Ejemplo de trabajo mínimo:

 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()
about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!