[英]Flask json response is failing in the ajax success handler
我有一个运行Flask的Python服务器和一个运行JavaScript Ajax调用的Page,并且在Ajax成功处理程序(.done(...))中不断收到错误,但未能解析发送给它的jsonified响应?
我已经尝试过jsonify'ing一个字典,只是一个字符串,以及其他各种方法。 似乎没有任何作用。
这是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)
这是每次都会失败的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;
});
}
我希望它可以将firstNameBlurb更改为“ TEST”,但它跳转到.fail处理程序并将错误文本更改为J:undefinederror 0-error
这是对我有用的后端更正:
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)
我没有太多时间,所以我使用简单的cURL进行了测试:
curl -X POST -H 'Content-Type: application/json' -d '{"FirstName": "davide"}' http://localhost:5000/api/firstname
输出为:
{
"story": "davide can be a given name or a surname."
}
我的天啊。 原来这是跨站点脚本错误。
在我的URL中,我使用了:127.0.0.1:5000在我的JavaScript中,我使用了localhost:5000。
显然,这些不是同一回事,并导致Ajax抱怨:
从源' 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.