简体   繁体   English

Flask JSON响应在Ajax成功处理程序中失败

[英]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? 我有一个运行Flask的Python服务器和一个运行JavaScript Ajax调用的Page,并且在Ajax成功处理程序(.done(...))中不断收到错误,但未能解析发送给它的jsonified响应?

I've tried jsonify'ing a dictionary, just a string, and a variety of other methods. 我已经尝试过jsonify'ing一个字典,只是一个字符串,以及其他各种方法。 Nothing seems to work. 似乎没有任何作用。

Here's the Python server: 这是Python服务器:

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: 这是每次都会失败的JavaScript Ajax调用:

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 我希望它可以将firstNameBlurb更改为“ TEST”,但它跳转到.fail处理程序并将错误文本更改为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进行了测试:

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. 在我的URL中,我使用了:127.0.0.1:5000在我的JavaScript中,我使用了localhost:5000。

Apparently, those are NOT the same thing and caused the Ajax to complain: 显然,这些不是同一回事,并导致Ajax抱怨:

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. 从源' http://127.0.0.1:5000 '对' http:// localhost:5000 / api / firstname '处的XMLHttpRequest的访问已被CORS策略阻止:不存在'Access-Control-Allow-Origin'标头在请求的资源上。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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