简体   繁体   中英

Flask json response is failing in the ajax success handler

I have a Python server running Flask and a Page running a JavaScript Ajax call and I keep getting an error in the Ajax success handler (.done(…)) failing to parse the jsonified response sent to it?

I've tried jsonify'ing a dictionary, just a string, and a variety of other methods. Nothing seems to work.

Here's the Python server:

from flask import Flask, render_template, redirect, json, jsonify, request, Response

# Create an instance of Flask
app = Flask(__name__)

@app.route("/")
def home():
    return render_template("Page.html")

@app.route("/api/firstname", methods=['POST'])
def firstname():
    fname = request.form.get("FirstName")
    fnd = f'{fname} can be a given name or a surname.'
    jsonResponse = jsonify({"story": fnd})
    return jsonResponse

if __name__ == "__main__":
    app.run(debug=True)

And here's the JavaScript Ajax call that fails every time:

function LookupFirstName(firstname) {
  let fnb = document.getElementById("firstNameBlurb");
  fnb.innerText = "003 Researching " + firstname;
  $.ajax({
    url: "http://localhost:5000/api/firstname",
    type: "POST",
    data: {
      FirstName: firstname
    },
    dataType: "json"
  })
    .done(function(data) {
      let fnb = document.getElementById("firstNameBlurb");
      fnb.innerText = "TEST"; //data; //data.decode("utf-8");
    })
    .fail(function(jqXHR, textStatus) {
      let e = document.getElementById("error");
      e.innerText = "J: " + jqXHR.responseText;
      e.innerText += "error: " + jqXHR.status + "-" + textStatus;
    });
}

I expect it to change the firstNameBlurb to "TEST" but instead it jumps to the .fail handler and changes the error text to J: undefinederror 0-error

Here's the backend correction that worked for me:

from flask import Flask, render_template, redirect, json, jsonify, request, Response

# Create an instance of Flask
app = Flask(__name__)

@app.route("/")
def home():
    return render_template("Page.html")

@app.route("/api/firstname", methods=['POST'])
def firstname():
    json_data = request.get_json()
    fname = json_data['FirstName']
    fnd = f'{fname} can be a given name or a surname.'
    jsonResponse = jsonify({"story": fnd})
    return jsonResponse

if __name__ == "__main__":
    app.run(debug=True)

I didn't have much time so I tested it using simple cURL:

curl -X POST -H 'Content-Type: application/json' -d '{"FirstName": "davide"}' http://localhost:5000/api/firstname

Output was:

{
  "story": "davide can be a given name or a surname."
}

OMG. This turned out to be a cross-site scripting error.

In my URL I used: 127.0.0.1:5000 In my JavaScript I used localhost:5000.

Apparently, those are NOT the same thing and caused the Ajax to complain:

Access to XMLHttpRequest at ' http://localhost:5000/api/firstname ' from origin ' http://127.0.0.1:5000 ' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM