I am trying to send JSON from Javascript to a Python POST route using Flask. I believe the JSON is sending correctly to Python, except I am struggling to figure out how to access it. In my Python response variable after the POST route occurs, type(response)
prints <Response [200]>
. When I print dir(response)
I get
I see that there is a JSON method within this response, however when I print response.json()
, I receive the following error:
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
My Javascript and Python code is below. Appreciate any help.
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")