Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Sending A Json object through Fetch API to a Flask Server leads to a 400 Bad Request

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

Based on your code and the error message you are receiving, the issue might be related to the request header not being set correctly.

You are setting the Content-Type header in your JavaScript code to "application/json", which is correct. However, your Flask view function does not check the Content-Type header correctly. You can check it like this:

if request.is_json:
    data = request.get_json()
    print(data)
else:
    print("Request is not JSON")

This checks whether the request is in JSON format using the is_json property of the request object. If it is, then you can use the get_json() method to extract the data. If it’s not, you can print a message or return an error.

Additionally, you might want to add a try-except block to catch any errors that might occur when parsing the JSON data:

if request.is_json:
    try:
        data = request.get_json()
        print(data)
    except Exception as e:
        print("Error parsing JSON data:", e)
        return "Bad Request", 400
else:
    print("Request is not JSON")
    return "Bad Request", 400

This will catch any exceptions when parsing the JSON data and return a "Bad Request" error with a 400 status code.

I hope this helps!

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading