I’m sending form data using JavaScript through Ajax in Json format to the python script ( wsgiref ), so it can capture this data and return the response in json format. The problem I face boils down to a server error 500, where I can’t reach the objective of capturing the data and being able to return the answer, below is the code:
Ajax, Json Code :
<script>
const next = document.querySelector(".btn-large")
const text = next.innerHTML = "Seguinte"
next.onclick = function() {
let ws_safe_email = document.querySelector(".ws_input_email").value
const jsonData = {
"ws_safe_email": ws_safe_email
}
const jsonSend = JSON.stringify(jsonData)
const ajax = new XMLHttpRequest()
ajax.open("POST", "http://127.0.0.1:8080/", true)
ajax.setRequestHeader("Content-Type", "application/json")
ajax.send(jsonSend)
if(ajax.readyState === 4) {
if(ajax.status === 200) {
alert("Received Data")
}
}
}
</script>
Python Code :
from wsgiref.simple_server import make_server
# Module name : cgi -> ( https://docs.python.org/3/library/cgi.html#module-cgi )
import cgi, json
def apps(environ, start_response):
# Function -> Capture the request method:
v_mtd = environ["REQUEST_METHOD"]
# Function -> Capture the request form data:
v_inp = cgi.FieldStorage(environ["wsgi.input"], environ=environ)
if v_mtd == "GET":
# Acessa o arquivo static requisitado :
file = open("index.html", "r")
# Faz a leitura do arquivo :
sile = file.read()
status = "200 OK"
headers = [("Content-type", "text/html; charset=utf-8")]
start_response(status, headers)
# The returned object is going to be printed
return [str(sile).encode('utf-8')]
if v_mtd == "POST":
...
with make_server("", 8080, apps) as httpd:
print("Serving on port 8080...")
# Serve until process is killed
httpd.serve_forever()