2

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.

3
  • What happens when you try to access data['hello']? Commented Jan 9, 2019 at 9:09
  • data is None so I cannot index into it Commented Jan 9, 2019 at 9:10
  • wireshark or tcpdump or tcpflow may help to see what happened in the network. you can debug into flask to see what you get from the request. Commented Jan 9, 2019 at 10:59

1 Answer 1

1

I am having the same frustration, and you question helped solve my issue, by forcing get_json()

I did notice that the difference between my implementation and yours is:

from flask_cors import CORS
CORS(app)

https://flask-cors.readthedocs.io/en/latest/

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.