I'm trying to POST a JSON payload to a Flask server running on localhost:8080.
Javascript
fetch(SERVER_URL, {
method: 'POST',
mode: 'no-cors',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({"hello": "world"})
});
I'm using Python Flask for my server, and I just want to print the received JSON on the server side.
Python Flask
from flask import Flask
from flask import request
app = Flask(__name__)
@app.route('/route', methods = ['POST'])
def routeHandler():
data = request.get_json()
print(data)
return 'got it'
app.run(port = 8080)
The print statement is triggered, but data is None. After reading the Flask API documentation, I know that one of the reasons why data could be None is when the correct content type is not set on the request. To check this, I made the following change
data = request.get_json(force = True)
which bypasses the is_json() check and continues parsing. This worked, suggesting there's something wrong with my headers. However, I have ensured that my fetch request is consistent with the API documentation so I'm not sure where I'm going wrong.
I have sent the same request from Postman and it is successfully received on the server even without force = True. The only header generated in Postman is Content-Type: application/json.
Thanks for any assistance.
data['hello']?wiresharkortcpdumportcpflowmay help to see what happened in the network. you can debug into flask to see what you get from the request.