[英]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.