0

I have a Python Flask app setup like this:

@app.route("/")
def getlist():
    data = jsonify({"test": True, "name": "User",
                    "teststring": "Hello, World!"})

    return data

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5050, debug=True)

Its a very simple one that returns a jsonified dictionary on the root (/) of domain. I hosted this site as you can see on localhost:5050. Now when I use JavaScript to fetch this JSON using the fetch api like this:

fetch("http://localhost:5050", {
    mode: "no-cors", // I added this due to some other error, called cross origin something
})
    .then((blob) => blob.json())
    .then((data) => console.log(data));

I get this error in this console:

Uncaught (in promise) SyntaxError: JSON.parse: unexpected end of data at line 1 column 1 of the JSON data

but the Network tab shows 200 OK

network status response

an4s911
  • 411
  • 1
  • 6
  • 16
  • `200 ok` just means the response returned a 200 code. It doesn't mean the data is correct. May you please add the JSON response? – evolutionxbox Feb 15 '22 at 12:03
  • Yes, correct. I should've known that – an4s911 Feb 15 '22 at 12:04
  • `200` means only that server knows how to answer for this URL - but it doesn't mean that it has to send data which you expect. Maybe it runs different code or it sends error message. You should first check what you get in fetch using `console.log(blob)` – furas Feb 15 '22 at 12:05
  • I referred the **Questioned already answer** mentioned above. It didn't directly answer my question, but I read through the answers there and I saw some suggesting that if using express as backend do to enable CORS. So a quick google search for Flask solved it. The resources that helped me solved: https://stackoverflow.com/questions/26980713/solve-cross-origin-resource-sharing-with-flask pointed to http://flask-cors.readthedocs.org/en/latest/ – an4s911 Feb 15 '22 at 13:07
  • @an4s911 Glad you solved it. Be sure not to blindly copy the `response.headers.add('Access-Control-Allow-Origin', '*')`. Instead of the `'*'`, put the domain you want to make the call from there. – Ivar Feb 15 '22 at 13:10

0 Answers0