【发布时间】:2021-03-26 17:45:56
【问题描述】:
我正在尝试使用 Flask 将 JSON 从 Javascript 发送到 Python POST 路由。我相信 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")
【问题讨论】:
-
等等,这个网络服务器是在 5000 端口上运行的吗?因为如果是这样,那么我认为您想从
request(来自Flask)中读取以获取发布的数据,因为它目前似乎正在获取本身? -
这部分太让我头疼了,一直在努力掌握这些概念。所以,在发出请求并收到
None之后,我尝试了`print("json", request.json)`。 -
这两种语言之间有没有更好的交流方式?我只是希望将 JSON 数据从 Javascript 发送到该 Python 路由。我的 Javascript 中的 axios.post 网址可能是问题吗?
标签: javascript python html jquery json