I have this in React:
const payload = {
x : x,
y : y
}
fetch("http://localhost:8080/update_game", {
method: "POST",
body: JSON.stringify(payload)})
And this in Python:
@post('/update_game')
def update_game():
req = request.json
print(req);
I keep getting:
None
127.0.0.1 - - [24/Jan/2022 14:06:36] "POST /update_game HTTP/1.1" 200 0
I don't see what I would be doing different than all of the other examples I've been finding. payload
successfully logs in the console. I have CORS set up and working correctly in Python. I also tried adding contentType: application/JSON
to the react side. I don't see what I could be doing wrong here.
edit for clarity: I'm attempting to print out the json response in the terminal on the python side. I simply want to see that this response is going through.
I discovered this little bit, that does show something, but is not correct:
@post('/update_game')
def update_game():
req = request.forms
print(dir(req))
print(dict(req))
print(req)
the ouput:
{'{"x":"0","y":"6"}': ''}
And I also have this:
def update_game():
req = request.headers['Content-Type']
# print(dir(req))
# print(dict(req))
print(req)
output:
text/plain;charset=UTF-8
I'm pretty sure that should be application/JSON
Starting from scratch...
$ python3 -m venv venv
$ source venv/bin/activate
$ python -m pip install -U bottle
Create app.py
from bottle import post, request, run
@post('/echo')
def echo():
data = request.json
print(type(data))
return data # example to return the input
run(host='localhost', port=8080, debug=True)
Run python app.py
From a new terminal, I pass the Content-Type along with a payload to return
$ curl -H 'Content-Type: application/json' -d'{"x": 2, "y":4}' http://localhost:8080/echo
{"x": 2, "y": 4}
In the server logs, I see
<class 'dict'>
127.0.0.1 - - [24/Jan/2022 17:13:38] "POST /echo HTTP/1.1" 200 16
See this post for properly sending JSON from Javascript without it being text/plain
- Setting Content-Type in fetch request not working
I found one solution. Hopefully this one helps whoever is having the same issues.
import json
import io
@post('/update_game')
def update_game():
encoding = "UTF-8"
req = json.load(io.TextIOWrapper(request.body, encoding=encoding))
print(req)