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

Question:

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

Asked By: AldoGP5

||

Answers:

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!

You need to specify the full endpoint of what you are targeting.

from flask import Flask, request

# create the flask app
app = Flask(__name__)

# post endpoint
@app.route('/post', methods=['POST'])
def endpoint():
    data = request.get_json()
    
    return data

# run the app
if __name__ == '__main__':
    app.run(debug=True)
const endpoint = "http://127.0.0.1:5000/post";

// post request to endpoint
const response = fetch(endpoint, {
    method: "POST",
    headers: {
        "Content-Type": "application/json"
    },
    body: JSON.stringify({
        name: "John Doe",
    })
});

response.then(data => {
    data.text().then(text => {
        console.log(text);
    })
})
Answered By: JackJones
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.