personwholikestocode
personwholikestocode

Reputation: 561

Issues sending/interpreting JSON sent from Javascript to Python

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 enter image description here

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")

Upvotes: 1

Views: 110

Answers (1)

Scotty Jamison
Scotty Jamison

Reputation: 13129

It looks like you're mixing up a couple python libraries.

The requests python library is used for sending out HTTP requests, similar to axios in javascript. The flask python library is used for making an HTTP web server.

At the top of your file, you're doing import requests which imports the requests library, not the flask library. Later, you're telling the requests library to send a GET request to http://localhost:5000/api/get-lucky-num, then you're trying to get the JSON response from the result of that request.

What you were probably trying to do instead was from flask import request, which would import flask's request API. From there, you could do request.json to get the JSON data that was POSTed to this endpoint. You might have to set the 'Content-Type' header to 'application/json' in javascript when you send the request for flask to interpret it correctly. This can be done as follows:

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

See this stackoverflow answer for more information on getting the POST data from a flask response, and this page for more information on using axios.

Upvotes: 1

Related Questions