handle http post request with json by python script on iis
<p>i have trouble handling http post request with JSON as body of the request. 
i am running IIS with python as server script.</p>

<p>this is the code that makes request: </p>

<pre><code>var http = new XMLHttpRequest();

var url = "http://myurl.ext/py/script.py";

http.onreadystatechange = function() {
if(http.readyState == 4 &amp;&amp; http.status == 200) {
    console.log(http.responseText);
    }
}

data = {"field":"value", "number":5}

http.open('POST', url, true); 
http.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
http.send(JSON.stringify(data));
</code></pre>

<p>on server side i have: </p>

<pre><code>import cgi
import http.client

print("Content-Type: text/text")
print("")

print(cgi.parse())
print(http.client.HTTPResponse)
</code></pre>

<p>cgi.parse() gives empty string</p>

<p>http.client.HTTPResponse gives empty string</p>

<p>cgi.FieldStorage() gives empty string, but if i submit a form, it returns values of the input fields. </p>

<p>i want to send JSON data in the background to the script and return some processed values as JSON as well. </p>

<p>The <a href="https://docs.python.org/3/library/cgi.html#module-cgi" rel="nofollow"><code>cgi</code></a> module is designed primarily with form processing from a POST request, or query string parsing from a GET request, in mind. As such it does not really provide much that might help you process a JSON request.</p>

<p>Keep in mind that all the CGI script does is read data from the process' environment and its standard input. Thus you can just read the body of the POST from <code>sys.stdin</code>:</p>

<pre><code>#!/usr/bin/env python3

import sys
import json
from pprint import pprint

print('Content-Type: text/plain')
print()

try:
    data = json.load(sys.stdin)
    print("Received:")
    pprint(data)
except json.JSONDecodeError as exc:
    print('Failed to decode JSON request: {}'.format(exc))
</code></pre>

<p>All this script does is to decode the standard input as JSON and pretty print it back out in the response.</p>

<p>You might be better off looking at something more usable such as <a href="http://flask.pocoo.org/" rel="nofollow"><code>flask</code></a>, <a href="http://bottlepy.org" rel="nofollow"><code>bottle</code></a>, etc.</p>

python json iis post request