-4

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?

france1
  • 141
  • 2
  • 12
  • 1
    _"This json file..."_ - is a plain object. The only actual [JSON](https://www.json.org/json-en.html) in your question/script is the content of `storeDictionary` – Andreas Aug 16 '22 at 16:13
  • `objectWords` is just an *object*. Stringifying is what turns the object into JSON formatted *text*. The error message means that what the server sends back as response isn't in JSON format. You need something like `return json.dump({ success: True })` –  Aug 16 '22 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. – Andreas Aug 16 '22 at 16:14
  • What is line 74 in main.js? Is it `.then((response) => response.json())`? Description of the JSON tag: _"Before you ask a question, validate your JSON using a JSON validator such as JSONLint (https://jsonlint.com)."_ Have to done this with the server response? – jabaa Aug 16 '22 at 16:17
  • .catch((error) => { - line 74 @jabaa - just modified the file, not sure anymore, the catch is now line 72 so I think that was 74. – france1 Aug 16 '22 at 16:20
  • I guess the lines of the code in your editor and the evaluated code are not in sync. No JSON is parsed in the `catch` block. Could you do some debugging, create a [mcve] (remove everything unrelated and make the code complete) and post it? You should also add the server response. – jabaa Aug 16 '22 at 16:22
  • @Andreas in my eyes the object later is converted with JSON.stringify => `storeDictionary` and then => `const uploadjson = storeDictionary` and then sent – france1 Aug 16 '22 at 16:23
  • @jabaa what should I do with the server response? It doesn't even send the file. – france1 Aug 16 '22 at 16:24
  • 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 –  Aug 16 '22 at 16:24
  • `response.json()` parses the server response. That fails if the response doesn't contain valid JSON. Lint the response using [JSONLint](https://jsonlint.com). Do you have a specific programming question or are you looking for interactive debugging support? The latter doesn't work well on Stack Overflow. – jabaa Aug 16 '22 at 16:25
  • _"This results in:..."_ - Because a string is not a file... – Andreas Aug 16 '22 at 16:30
  • Just saw it - looks like my image didn't get uploaded (this results in...) – france1 Aug 16 '22 at 16:33
  • @Andreas so how do I upload it then? – france1 Aug 16 '22 at 16:35
  • Do you want to "upload" this JSON string or a file? – jabaa Aug 16 '22 at 16:38
  • Yeah sure. And it looks like that's working - what's not working is actually the flask thing - I will edit my post. – france1 Aug 16 '22 at 16:39
  • 1
    Question: _"Option A or B"_, Answer: _"Yes"_ o.O – Andreas Aug 16 '22 at 16:41
  • * @jabaa I want to upload this json string, – france1 Aug 16 '22 at 16:44
  • 2
    [`flask.request.files`](https://tedboy.github.io/flask/generated/generated/flask.Request.files.html) 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`](https://tedboy.github.io/flask/interface_api.incoming_request_data.html#flask.Request.get_json) – jabaa Aug 16 '22 at 16:46
  • As far as I can tell you're sending `{ "a": "", "b": "", "c": "", "d": "", "": "" }` so no file. Accessing the file object server-side makes no sense unless you actually send a file. Main problem earlier: you're returning a *string* ("success") so you need `response => response.text()` in your JS code. The original error occured because you told the browser to JSON parse "success", which causes an error –  Aug 16 '22 at 16:47
  • TBH, I don't know what you expect `let formData = new FormData(); fetch(url, {method: "POST", headers: {'Content-Type': 'application/json'}, body: formData})` to do. You're sending a multipart/form-data request with a JSON header. I've never seen this. `flask.request.files` can't read it because of the wrong header and `flask.request.get_json` can't read it because of the wrong format. Your question is really confusing because of contradicting code snippets. You should clean it up. It's not clear which snippets you're actually using. And you can remove the screenshots. They are not useful. – jabaa Aug 16 '22 at 16:54
  • @jabaa I think that's what I needed. I will try to fix it later. – france1 Aug 16 '22 at 16:58
  • https://stackoverflow.com/questions/53240205/request-files-400-bad-request-in-flask – James Aug 16 '22 at 17:03
  • @jabaa please write an answer. I fixed it. The json is now successfully read and the server response is 200. Your answer should be about flask.request.get_json - just a short one so I can mark that answer as solved. And maybe about how to confirm everything went well on the client side. – france1 Aug 16 '22 at 17:03
  • 1
    I wouldn't answer this question. I don't consider it useful. It's really confusing and not helpful for future users. – jabaa Aug 16 '22 at 17:06
  • - so I should delete this? No, I'm going to rewrite it tomorrow, then you might answer, and if not I will write an answer. @jabaa – france1 Aug 16 '22 at 17:10
  • Seconded, there's no need to keep this question here, let alone post an answer. Sending JSON and trying to read a file server-side is obviously going to fail. –  Aug 17 '22 at 11:06
  • 1
    Please post logs, error messages and code as text, not as images. – jabaa Aug 17 '22 at 13:52
  • 1
    The downvotes are still valid. This question is lacking basic research effort. There are dozens of duplicates like [Get json from request flask](https://stackoverflow.com/questions/43126956/get-json-from-request-flask), [How to POST JSON data with Python Requests?](https://stackoverflow.com/questions/9733638/how-to-post-json-data-with-python-requests), [How to get POSTed JSON in Flask?](https://stackoverflow.com/questions/20001229/how-to-get-posted-json-in-flask) – jabaa Aug 17 '22 at 13:54
  • 1
    Hover the downvote button: _"This question does not show any research effort"_ You could search for "flask request json" to find dozens of duplicates. That's basic research effort. Images of code, logs and error messages are a downvote reason. – jabaa Aug 17 '22 at 13:57
  • @jabaa I hope you know English - because I clearly researched. With research they don't mean duplicates but research in the own code, finding bugs etc. - and I did that – france1 Aug 22 '22 at 11:25
  • [How much research effort is expected of Stack Overflow users?](https://meta.stackoverflow.com/questions/261592/how-much-research-effort-is-expected-of-stack-overflow-users) _"A lot. Asking a question on Stack Overflow should be the last step in your process for finding an answer ... You want to - Search. Like mad."_ Searching the web with your favorite search engine and clicking some results is part of this basic research effort. The first three results of my search engine for "flask request json" contain two Stack Overflow duplicates. – jabaa Aug 22 '22 at 11:34
  • Reading documentation, e.g. [flask.request.files](https://tedboy.github.io/flask/generated/generated/flask.Request.files.html) and [flask.request.get_json](https://tedboy.github.io/flask/interface_api.incoming_request_data.html#flask.Request.get_json) is also part of this research effort and should be done before asking a question. – jabaa Aug 22 '22 at 11:40

1 Answers1

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!

france1
  • 141
  • 2
  • 12