-3

How do I send a json POST request using Javascript and read it on a flask server?

Last approach (reference):

const uploadjson = storeDictionary const url = "/uploadset/"+setName fetch(url, {method: 'POST', // or 'PUT' headers: { 'Content-Type': 'application/json', }, body: uploadjson}) .then((response) => response.json()) .then((data) => { console.log('Success:', uploadjson); }) .catch((error) => { console.error('Error:', error); console.log("Data:", uploadjson) }); 

It results in the following error message: enter image description here

Here's a part of the python code (flask) I wrote with help from the documentation:

@app.route("/uploadset/<name>", methods=['GET','POST']) def uploads(name): if flask.request.method == "POST": print("Upload!") if 'id' in flask.session: if flask.session['id'] in client: sessid = flask.session['id'] if name != "": print("flask.request.files", flask.request.files) file = flask.request.files['file'] try: if processUploadedSet(): error = False success = True 

This results into a "server didn't understand your request".

I found out that the flask server is the problem:

Here's the server log: enter image description here

If I return an empty string on the server the request works 'fine'. How do I read json data using flask which was sent using the javascript?

32
  • 1
    "This json file..." - is a plain object. The only actual JSON in your question/script is the content of storeDictionary Commented Aug 16, 2022 at 16:13
  • 1
    "I made a site which looks like this:..." - Which is not relevant for the question. The markup on the other hand might contain some relevant information. Commented Aug 16, 2022 at 16:14
  • 1
    There's no such thing as a JSON object. You called an object "json file", both words are wrong. It's neither json nor a file, it's an object in memory. Doesn't matter, the issue is response.json() while the response isn't JSON Commented Aug 16, 2022 at 16:24
  • 1
    Question: "Option A or B", Answer: "Yes" o.O Commented Aug 16, 2022 at 16:41
  • 2
    flask.request.files reads the files from multipart/form-data request, but the client sends a simple JSON request. You can read it with flask.request.get_json Commented Aug 16, 2022 at 16:46

1 Answer 1

0

You can read a json response in flask using flask.request.get_json

Simply replace file = flask.request.files['file']

with file = flask.request.get_json(cache=False)

Sending a json POST request is not the same as sending a file!

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.