我正在尝试使用Flask将JSON从Javascript发送到Python路由。我相信JSON发送给Python是正确的,只是我很难找到如何访问它。在POST路由发生后,在我的Python变量中,type(response)打印<Response [200]>。当我打印dir(response)时

我看到在这个响应中有一个JSON方法,但是当我打印response.json()时,我会收到以下错误:
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)我的Javascript和Python代码如下。感谢你的帮助。
async function processForm() {
const luckyNumObj = {num: {fact: "text is here", num: 3}, year: {fact: "text is here", year: 1990}};
console.log("luckyNumObj:", JSON.stringify(luckyNumObj))
await axios.post("/api/get-lucky-num", JSON.stringify(luckyNumObj))
};
processForm()
from flask import Flask, render_template, redirect, session, request, jsonify
import json
import requests
from werkzeug.exceptions import Unauthorized
app = Flask(__name__)
app.config['SECRET_KEY'] = "shhhhh"
@app.route("/")
def homepage():
"""Show homepage."""
return redirect("/api/get-lucky-num")
@app.route("/api/get-lucky-num", methods=["GET", "POST"])
def json_api():
"""JSON API Endpoint"""
if request.method == 'POST':
response = requests.get('http://localhost:5000/api/get-lucky-num')
data = response.json()
print("data", data)
return render_template("index.html")
return render_template("index.html")发布于 2020-12-16 04:33:31
看起来你把几个python库混在一起了。
HTTP库用于发送请求请求,类似于javascript中的axios。HTTP库用于制作HTTP服务器。
在文件的顶部,您正在执行import requests,它导入请求库,而不是烧瓶库。稍后,您告诉请求库向http://localhost:5000/api/get-lucky-num发送一个GET请求,然后尝试从该请求的结果中获取JSON响应。
您可能尝试做的是from flask import request,它将导入烧瓶的request。在那里,您可以执行request.json来获取POSTed到这个端点的JSON数据。当您发送烧瓶请求以正确解释时,您可能必须在javascript中将‘Content’标头设置为'application/json‘。这样做的办法如下:
await axios.post("/api/get-lucky-num", JSON.stringify(luckyNumObj), {
headers: { "content-type": 'application/json' },
})https://stackoverflow.com/questions/65316931
复制相似问题