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

328
Views
Flask & NextJS - CORS no funciona para POST

Estoy sirviendo mi modelo de aprendizaje automático en Flask como una solicitud POST.

Puedo realizar con éxito una solicitud POST en Postman, sin embargo, en el cliente, recibo un error CORS cuando intento obtener ese punto final en Siguiente.

Tengo el siguiente server.py

 from flask import Flask, request, jsonify import pickle from flask_cors import CORS app = Flask(__name__) cors = CORS(app) @app.route('/predict', methods=['POST']) def predict(): if request.method == 'POST': data = request.get_json() sentence = data['sentence'] vectoriser, LRmodel = load_models() if vectoriser and LRmodel: vector = vectoriser.transform([sentence]) prediction = LRmodel.predict(vector) # return jsonify({'prediction': str(prediction[0])}) if prediction[0] == 1: return jsonify({'prediction': 'Positive'}) else : return jsonify({'prediction': 'Negative'}) else: return jsonify("Error") return 'Error' if __name__ == '__main__': app.run(debug=True)

Así es como estoy tratando de llamar a este punto final en el cliente

 const Sentiment = (props: any) => { return ( <> <h1 style={{ textAlign: 'center' }}>Sentiment</h1> <div style={{ textAlign: 'center' }}> <form action="/sentiment" method="POST" onSubmit={handleSubmit}> <input type="text" name="sentiment" /> <button type="submit">Submit</button> </form> </div> </> ) } const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => { e.preventDefault() console.log(e.currentTarget.sentiment.value) const res = await fetch('http://127.0.0.1:5000/sentiment', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ sentence: e.currentTarget.sentiment.value }), }) await res.json() } export default Sentiment

Recibo este error: el acceso para buscar en 'http://127.0.0.1:5000/sentiment' desde el origen 'http://localhost:3000' ha sido bloqueado por la política de CORS: la respuesta a la solicitud de verificación previa no pasa el control de acceso comprobar: No tiene el estado HTTP ok.

Además, cuando envío el formulario, obtengo "OPCIONES / sentimiento HTTP / 1.1" 404 - En lugar de un POST

¿Alguna idea sobre lo que estoy haciendo mal?

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

intenta configurar un constructor como este

 app = Flask(__name__) cors = CORS(app, resources={r"/*": {"origins": "*"}})

si eso no funciona, intente agregar el decorador cross_origin

 from flask_cors import CORS,cross_origin @app.route('/predict', methods=['POST']) @cross_origin() def predict(): if request.method == 'POST': data = request.get_json() sentence = data['sentence'] vectoriser, LRmodel = load_models() if vectoriser and LRmodel: vector = vectoriser.transform([sentence]) prediction = LRmodel.predict(vector) # return jsonify({'prediction': str(prediction[0])}) if prediction[0] == 1: res = jsonify({'prediction': 'Positive'}) res.headers.add("Access-Control-Allow-Origin", "*") return res else : res = jsonify({'prediction': 'Positive'}) res.headers.add("Access-Control-Allow-Origin", "*") return res else: return jsonify("Error") return 'Error'
over 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!