I was trying to send some JSON data to the sever following some online articles and the official flask documentation, but I keep getting a 400 error. What I've tried hasn't worked so far.
I have read that if flask doesn't get properly formated JSON data it pushes this error and also that the read of the request must specify Content-Type header as application/json or else the same happens.
I copied some of my code off the official Documentation and this is what i have so far:
a view function inside my flask application:
@main.route('/test', methods=['GET','POST'])
def test():
if request.method == 'POST':
print(request.method)
print(request.headers.get('Content-Type'))
print(request.is_json)
#this gets me the 400 when run
#print(request.json)
return render_template('test.html')
the following scrip tag inside test.html:
<script>
let data = {"data": "Hello World!"}
document.querySelector('#main').addEventListener('click', function () {
fetch('/test', {
method: "POST",
body: JSON.stringify(data),
headers: {"Content-Type": "application/json"},
credentials: "same-origin"
})
.then(response => console.log(response.json))
})
</script>
Every time I hit the button to POST the data I get the following showing in my terminal
POST text/plain;charset=UTF-8 False
So I assume what is causing all of this is that the Content-Type header of the HTTP request is not setting properly.
Any ideas on how I could fix this would be apreciated
Via Active questions tagged javascript - Stack Overflow https://ift.tt/TOctYwA
Comments
Post a Comment