Forums

Passing Data Between Javascript and Flask with POST

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);
    }
});

Do you see any errors in the browser dev tools console when you enter some data to the input field?

Also -- you should probably fix the js code to resolve the JSON from the promise returned by fetch and then read the value of the answer. See: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch.

Thanks for the advice!

The issue appears to have been with authentication via cors and https - this did throw an errror in the JS console.

I changed the request to http (no ssl) and the POST worked fine and returned values.

Thanks again.

Glad you got that working!