This is my js function:
btn = document.getElementById('submit-button')
btn.addEventListener("click",submitForm)
function submitForm(){
fetch('http://localhost:5000/diagnose', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ symptoms: symptoms, email: loggedInUser.email }),
})
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(data => {
if (resultDiv) {
displayResults(data, symptoms);
}
})
.catch((error) => {
console.error('Error:', error);
if (resultDiv) {
resultDiv.innerHTML = '<p style="color: red;">An error occurred while processing your request. Please try again.</p>';
}
});
}
This is my server code. I’ve tried to include what the method I am calling, and my imports and anything that might be relevant.
from flask import Flask, request, jsonify, send_from_directory
import json
import os
import traceback
app = Flask(__name__)
ALLOWED_ORIGIN = os.environ.get('ALLOWED_ORIGIN', 'http://localhost:5500')
# Configure logging
logging.basicConfig(level=logging.DEBUG)
# Path to users.json and history file
history_file_path = os.path.join(os.path.dirname(__file__), 'history.json')
users_file_path = os.path.join(os.path.dirname(__file__), 'users.json')
# Middleware function to handle CORS headers
def add_cors_headers(response):
# Only allow requests from your frontend domain
response.headers['Access-Control-Allow-Origin'] = 'http://localhost:5500'
response.headers['Access-Control-Allow-Methods'] = 'GET, POST, OPTIONS'
response.headers['Access-Control-Allow-Headers'] = 'Content-Type, Authorization'
return response
# Register the after_request handler
@app.after_request
def after_request(response):
return add_cors_headers(response)
# Handle OPTIONS requests
@app.route('/', defaults={'path': ''}, methods=['OPTIONS'])
@app.route('/<path:path>', methods=['OPTIONS'])
def handle_options(path):
return '', 204
# Diagnose route
@app.route('/diagnose', methods=['POST'])
def diagnose():
data = request.json
symptoms = data.get('symptoms', '')
email = data.get('email', '')
diagnosis, recommendation = diagnose_and_recommend(symptoms)
# save history
history = read_history()
history['history'].append({
"email": email,
"date": datetime.now().isoformat(),
"symptoms": symptoms,
"diagnosis": diagnosis,
"recommendation": recommendation
})
write_history(history)
return jsonify({
"diagnosis": diagnosis,
"recommendation": recommendation
})
# Static files route
@app.route('/<path:filename>')
def serve_static_files(filename):
return send_from_directory('../', filename)
if __name__ == '__main__':
app.run(debug=True)
I have tried to allow the headers as you’ll see in the method labelled middleware but I am unfamiliar with cors. I would like to do away with it completely, but I don’t know how to get a response from my python file. I don’t know if it matters but my app.py is in a backend folder, while the js is in the root folder.