0

My Flask API is supposed to process text query sent in a POST request and respond with a JSON. I send the POST request using the JavaScript fetch API.

function getQueryResults(){
    let query = queryInput.value;
    statusTextField.innerHTML = "Processing query \"" + query + "\"...";
    fetch('http://localhost:5000/', {
        method: 'POST',
        body: JSON.stringify({"query": query}),
        mode: 'no-cors',
    }).then((data) => console.log(data))
}

And this is the Flask endpoint (sending a placeholder JSON).

@app.route('/', methods=['POST'])
def get_index():
    return Response(json.dumps((1,2,3)), mimetype='application/json')

Strangely, though, the response logged by console.log() contains no body and is of type opaque instead of JSON.

Response {type: "opaque", url: "", redirected: false, status: 0, ok: false, …}
body: null
bodyUsed: false
headers: Headers {}
ok: false
redirected: false
status: 0
statusText: ""
type: "opaque"
url: ""
__proto__: Response

What have I done wrong?

2 Answers2

0

In flask, if you want to return a response, there is no need to create a Response() object since Flask does this automatically on return. This should do the trick:

@app.route('/', methods=['POST'])
def get_index():
    return json.dumps((1,2,3))

This should return a response with status code 200, and the JSON content in the body.

A better explanation of this is available in the docs

Daan Sneep
  • 71
  • 1
  • 5
  • I tried `return json.dumps((1,2,3))` and it gives the same result. I suspect the problem lies in the JS code, namely Flask sends it correctly but JS reads it incorrectly. – Piotr Makarewicz Jun 02 '21 at 15:45
0

I managed to solve the problem myself. It was mode: "no-cors" that caused it, as says the answer here. I removed mode: "no-cors" from JS code and added

from flask_cors import CORS
CORS(app)

to the backend.