I have looked at these Stack Overflow links Flask request.get_json() raise BadRequest, Get raw POST body in Python Flask regardless of Content-Type header, and How to get POSTed JSON in Flask?; however, they don't answer my problem. When I use Postman, Python, or curl, my flask code works; however, when I use JavaScript, it doesn't work and I get the BadRequest error. April
does print at first; however, the error pops up on the web page. When I try to run json.loads(request.data, strict=False)
I get this jinja2 error: json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
. I think it might be the Javascript code I am using. Is it possible that concurrently running the request and the form submission might be the problem?
routes.py
@app.route('/calendar/', methods=['GET', 'POST'])
def calendar():
if request.method == 'POST':
data = request.get_json(force=True)
print(data['month'])
if form.validate_on_submit():
pass
html
<form action="" onsubmit="myFunction()" method="POST">
</form>
function myFunction() {
var data = "{\"month\":\"April\"}";
var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.addEventListener("readystatechange", function() {
if(this.readyState === 4) {
console.log(this.responseText);
}
});
xhr.open("POST", window.location.href);
xhr.setRequestHeader("Content-Type", "application/javascript");
xhr.setRequestHeader("Cookie", "session=eyJfZnJlc2giOmZhbHNlLCJjc3JmX3Rva2VuIjoiNmM5MmIxNmFkYWIyMWZmZjk3MWE4MmJkZTViNTc1M2ZmMDNiY2MxNyJ9.Xo0X5Q.bzl4ihYLaHjUqmiIc6WCwFUOP_8");
xhr.send(data);
}
EDIT#####
content = request.get_json(silent=True)
print(content['month'])
prints None