【问题标题】:Issues sending/interpreting JSON sent from Javascript to Python发送/解释从 Javascript 发送到 Python 的 JSON 的问题
【发布时间】: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


【解决方案1】:

看起来你正在混合几个 python 库。

requestspython 库用于发送 HTTP 请求,类似于 javascript 中的 axios。 flask python 库用于制作 HTTP 网络服务器。

在文件的顶部,您正在执行import requests,它导入请求库,而不是烧瓶库。稍后,您告诉 requests 库向 http://localhost:5000/api/get-lucky-num 发送 GET 请求,然后您尝试从该请求的结果中获取 JSON 响应。

您可能试图做的是from flask import request,它将导入flask 的请求API。从那里,您可以执行 request.json 以获取已发布到此端点的 JSON 数据。当您发送烧瓶请求以正确解释它时,您可能必须在 javascript 中将“Content-Type”标头设置为“application/json”。这可以按如下方式完成:

await axios.post("/api/get-lucky-num", JSON.stringify(luckyNumObj), {
  headers: { "content-type": 'application/json' },
})

有关从烧瓶响应中获取 POST 数据的更多信息,请参阅this stackoverflow answer,有关使用 axios 的更多信息,请参阅this page

【讨论】:

  • 谢谢你。开始有了更强的把握。你知道我如何将 Content-Type 标头更改为 application/json 吗?当我打印 request.get_json() 和 request.json 时,我收到“无”。当我打印 request.get_json(force=True) 时,我得到了要打印的正确 JSON,但是我的浏览器显示:Bad Request Failed to decode JSON object: Expecting value: line 1 column 1 (char 0) 来自您的链接:“The请求必须具有 application/json 内容类型,或使用 request.get_json(force=True) 忽略内容类型”。看来我可能只需要将“内容类型”标头设置为 json?
  • 我更新了问题以展示如何使用 axios 设置 Content-Type 标头的示例 - 希望对您有所帮助。
猜你喜欢
  • 2012-08-11
  • 1970-01-01
  • 1970-01-01
  • 2016-11-24
  • 2019-12-11
  • 2015-12-13
  • 1970-01-01
  • 1970-01-01
  • 2019-02-28
相关资源
最近更新 更多