I've spent hours messing around with this... and I don't understand why I'm getting an undefined response when I use Javascript to make a request. My flask app is extremely basic and looks like the following:
@app.route('/timespent', methods=['GET', 'POST'])
def calculateAvgReadTime():
return jsonify({'result':'Success'})
The Javascript code I'm using to make a request to this endpoint is the following:
var xhr = new XMLHttpRequest();
// Setup our listener to process compeleted requests
xhr.onreadystatechange = function () {
console.log(xhr.status)
// Only run if the request is complete
if (xhr.readyState !== 4) return;
// Process our return data
if (xhr.status >= 200 && xhr.status < 300) {
// What do when the request is successful
console.log(JSON.parse(xhr.responseText));
}
};
xhr.open('GET', 'https://xxxxx.herokuapp.com/timespent');
xhr.setRequestHeader("Content-Type", "application/json");
xhr.send();
What's confusing is the following:
if I use Python or software like Insomnia, then the request is returned as expected and nothing is wrong - this is what makes me think something is wrong with the Javascript...
When I change the URL in the Javascript to "https://jsonplaceholder.typicode.com/todos/1", it works as expected and returns a json - this is what makes me think that my flask app is wrong...
Some help would be greatly appreciated.