I'm trying to pass data from a Javascript UX to a Flask app and then pass response data back to the webpage/Javascript. The webpage loads "base.html" and the Javascript runs fine. It appears to be failing on the fetch/POST command in Javascript when it attempts to post back to the Flask app. I am able to get the data from the input field and can see that it is formatted properly ahead of the fetch/POST, but cannot get a response from Flask.
Any help much appreciated - thanks!
Flask Code from flask import Flask, render_template, jsonify, request
app = Flask(__name__)
@app.route('/', methods=['GET'])
def index():
if request.method == 'GET':
return render_template("base.html")
@app.route('/predict', methods=['POST'])
def predict():
if request.method == 'POST':
text = request.get_json().get("name")
message = {"answer": text}
return jsonify(message)
if __name__ == "__main__":
app.run(debug=True)
Javascript Code
const inputField = document.getElementById("input");
document.getElementById("input").addEventListener("keyup", function(event) {
if (event.keyCode === 13) {
let input = inputField.value;
let user = {name: input};
let response = fetch("https://mysite.pythonanywhere.com/predict", {
method: 'POST',
mode: 'cors',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(user)
});
let result = response.json();
alert(result.answer);
}
});