0

I am trying to send an array of module names and an array of marks to a function running on a python flask server.

  function getClassification()
  {
    const modulesArray = [
      document.getElementById('module_1').value,
      document.getElementById('module_2').value,
      document.getElementById('module_3').value,
      document.getElementById('module_4').value,
      document.getElementById('module_5').value
    ]
    const marksArray = [
      document.getElementById('mark_1').value,
      document.getElementById('mark_2').value,
      document.getElementById('mark_3').value,
      document.getElementById('mark_4').value,
      document.getElementById('mark_5').value
    ]
    let xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
      if (this.readyState == 4 && this.status == 200) {
        var j = JSON.parse(this.response);
      }
    };
    xhttp.open("GET",classifyModulesURL+"?modules="+modulesArray+"&marks="+marksArray);
    xhttp.send();
    return;
  }

When the flask server recieves the information, it is being treated as a string.

modules = request.args.get('modules')
print(modules)
marks = request.args.get('marks')
print(marks)
print(type(marks))

Outputs


CSC3021,CSC4302,CSC3299,CSC5678,CSC7623
45,66,43,54,78
<class 'str'>

I could do string manipulation on the python end to convert the strings to lists, but I thought the sending of the javascript array would preserve the structure. Have I done something wrong?

Thanks

modules = request.args.get('modules')
print(modules)
marks = request.args.get('marks')
print(marks)
print(type(marks))

Outputs


CSC3021,CSC4302,CSC3299,CSC5678,CSC7623
45,66,43,54,78
<class 'str'>

1 Answers1

0

This is because you are sending data as a query argument ( www.example.com?arg1=val1&arg2=val2 )which can only be sent as a string since they are part of the url. To preserve a list you should create a json object to be sent in the body of the POST request. At the same time the request must be handled correctly on the server side, i.e. you will no longer have to access the http request arguments, but its json content.

Look how to handle json request with flask.

Look how to post json with XMLHttpRequest

Matteo Pasini
  • 1,787
  • 3
  • 13
  • 26
  • I get this error: Access to XMLHttpRequest at 'http://127.0.0.1:8004/' from origin 'http://127.0.0.1' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. – Desiree Armfelt Nov 07 '22 at 11:31
  • This is another very common mistake, I am sure that on google and also on stack overflow you will find a lot of information about it – Matteo Pasini Nov 07 '22 at 11:33