0

I created a flask server with the following code

from flask import Flask

app = Flask(__name__)

defaults = {
    "status": "running",
    "session": "loggedIn"
}

jsonObject =  json.loads(json.dumps(defaults))


@app.route('/api/data/')
def apiData():
    return jsonObject

app.debug=True
app.run(host='127.0.0.1', port=6464, threaded=True)

And then I crearte a web page with the following javascript

  function api(url) {
    var sender = new XMLHttpRequest;
    sender.open('GET',url)
    sender.send()

    return sender
  }

var serverData = api('/api/data')
console.log(serverData.responseText)

And in the console, it returns <empty string>

Heres what I've tried:

  • Checked the function in the browsers developer console and it worked dev console

  • I thought to check the flask logs and found that it reponded with 308 which meant redirection, after a little research I found that CORS maybe the problem, so I added this code to flask app

from flask_cors import CORS
CORS(app)

But it still didnt work. It still returns empty string

  • Checked with curl and it worked fine
$ curl http://localhost:6464/api/data/
{
  "session": "loggedIn", 
  "status": "running"
}
      
  • Modified the javascript like this
var apiData = api('/api/data/') //didn't work
//------------------------------------------
var apiData = api('http://localhost:6464/api/data/') //didn't work
//------------------------------------------
var apiData = api('http://127.0.0.1:6464/api/data/')//didn't work

My question is, where is my data? Why does it returns empty string when run by the webpage and why it returns the actual data when run by the browsers dev console. My browser is firefox BTW

  • JavaScript can run functions asynchronously and you may try to get data before it even get data from server. You have to assing function which will be executed `on success` and this functions should get data. – furas Jul 18 '21 at 22:53

0 Answers0