0

I would like to setup a simple way of having javascript in a client web page to communicate with a python server. The final goal is to create a simple web-browser based game for 2-4 players which access some page, and where they can do something (and see some graphics generated by three.js). Therefore, I would like to have the client in javascript, and the backend in python (because python is great).

My previous questions are here and here. Now I tried yet another example following this description but again it didn't work.

Here is the full code, index.html:

<html>
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
    <script type="text/javascript">
    // setup some JSON to use
    var cars = [
      { "make":"Porsche", "model":"911S" },
      { "make":"Mercedes-Benz", "model":"220SE" },
      { "make":"Jaguar","model": "Mark VII" }
    ];

    window.onload = function() {
      // setup the button click
      document.getElementById("theButton").onclick = function() {
        doWork();
      };
    };

    function doWork() {
      // ajax the JSON to the server
      $.post("receiver", cars, function(){

      });
      // stop link reloading the page
     event.preventDefault();
    }
    </script>
    This will send data using AJAX to Python:<br /><br />
    <a href="" id="theButton">Click Me</a>
  </body>
</html>

and here is the python code:

import sys

from flask import Flask, render_template, request, redirect, Response
import random, json

app = Flask(__name__)

@app.route('/')
def output():
    # serve index template
    return render_template('index.html', name='Joe')

@app.route('/receiver', methods = ['POST'])
def worker():
    # read json + reply
    data = request.get_json() # HERE
    print(data)
    result = ''

    for item in data:
        # loop over every row
        result += str(item['make']) + '\n'

    return result

if __name__ == '__main__':
    # run!
    app.run()

The problem is that the data received in the python code (HERE) the data is None.

I would appreciate ideas on how this can be fixed.

Alex
  • 41,580
  • 88
  • 260
  • 469
  • See this answer: https://stackoverflow.com/questions/20001229/how-to-get-posted-json-in-flask You must set the mimetype of your request to 'application/json' for request.get_json() to work. – aroville Jul 24 '17 at 10:12
  • The solution suggests to use the method `request.get_json()` which I am using already. Otherwise, please provide the exact code snippet on how to fix my code. – Alex Jul 24 '17 at 10:42

1 Answers1

0

See this answer: How to get POSTed json in Flask?

The problem comes from your jQuery post request: the default mimetype is "application/x-www-form-urlencoded" when using $.post, try using $.ajax with contentType "application/json", otherwise Flask will be unable to know that the data you send is JSON, and will return None when you call get_json()

Another idea is to use data instead of get_json(), then parse the result:

data = request.data
dataDict = json.loads(data)
aroville
  • 53
  • 8
  • Maybe it works, but nothing is printed out. When I redirect the printout to `sys.stderr` I get the error: `TypeError: the JSON object must be str, not 'bytes` – Alex Jul 25 '17 at 12:07