Home>

macOS
python3.7
Flask 1.1.1

I'm making a simple app to load a local csv file with Flask + html + javascript and visualize the data in a browser.

When sending a GET request with XMLHttpRequest from js to Flask's api, the following error occurs when fetching the data included in the response.

Thank you for helping us identify the cause of this error.

Error message
null is not an object (evaluating 'request.response ["data"]')
EventListener log
{x1: Array, x2: Array, y: Array} # At this point, you get the expected response
Applicable source code
unction reqListener () {
  console.log (this.response);
}
function openRequest (requestURL) {
    var request = new XMLHttpRequest ();
    request.addEventListener ("load", reqListener);
    request.open ('GET', requestURL);
    request.responseType = 'json';
    request.send ();
    return request;
}
function getData (request, col) {
   return request.response [col];
  }
var documentElement = document.getElementById ("file_info")
var filename = documentElement.getAttribute ("filename")
var x_col = documentElement.getAttribute ("x_col")
var y_col = documentElement.getAttribute ("y_col")
var requestURL = 'http://127.0.0.1:5000/api/data/' + filename;
var request = openRequest (requestURL);
console.log (typeof (request.response ["data"]) == 'object') # An error occurs here: null is not an object (evaluating 'request.response ["data"]')

I took a quick look at the documentation around Mozilla's XHR, but I couldn't identify the cause.
https://developer.mozilla.org/en/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest

  • Answer # 1

    openRequest is a return request, but it is an asynchronous process
    addEventListener (You have to wait for promise with "load"

    If you can abandon your old browser, it's reasonable to do it with fetch

  • Answer # 2

    Isn't it returning the intended content?

    console.log (request.response ["data"])


    However, I think that it is good to check the contents or check the response with the development tool of the browser.

  • Answer # 3

    I was able to solve the answer with hints. Thank you, everyone.
    As yambejp said, I tried to solve it with fetch, but because I didn't know how to handle the promise object, I solved it with a method using XMLHttpRequest. How is that code? Changed to process to set request.onload in openRequest and plot at loading.

    function openRequest (requestURL, x_col, y_col) {
        var request = new XMLHttpRequest ();
        request.open ('GET', requestURL);
        request.responseType = 'json';
        request.onload = function () {
          var xcol_idx = getColumnIndex (request.response ["columns"], x_col);
          var ycol_idx = getColumnIndex (request.response ["columns"], y_col);
          plot (request.response ["data"], xcol_idx, ycol_idx);
        }
        request.send ();
        return request;
    }
    function getColumnIndex (columns, name) {
      for (var i = 0;i