Search code examples
javascriptpythonrequestcgi

How to receive POST request from Javascript in Python CGI script?


I have a website with a big form. When I first made the website, I was using a GET request to send the form values to a Python CGI script (using the JavaScript fetch function). In the Python script, I could read the data with parameters = cgi.FieldStorage().

Since a GET request has a limited payload size, I had to switch to a POST request because that request type has no limit.

I changed my JavaScript fetch function to the following to make a POST request:

  fetch('../../cgi-bin/saveFormAnswers.py', {
    method: 'POST',
    body: JSON.stringify(data),
    headers: {
      'Content-type': 'application/json; charset=UTF-8',
    }
  })
    .then(antwoord => antwoord.json())
    .then(data => {
      console.log("Return data Python:")
      console.log(data);
    }
    );

However, I can't seem to get the data in the Python CGI script. cgi.FieldStorage() doesn't work anymore. How do I get the POST payload in the Python script and how do I send a (JSON) dictionary back as a response to the POST request?

I'm not using any frameworks like Flask.

EDIT: I came to the conclusion it's related to the JavaScript code and that cgi.FieldStorage() should work. Instead of letting JavaScript do the POST request, I set up the POST request directly in the HTML form which worked just fine without any issues. I'm still trying to figure out what's wrong with my JavaScript code.


Solution

  • Fixed it by using sys.stdin instead of cgi.FieldStorage().

    data = ""
    
    if int(os.environ.get('CONTENT_LENGTH', 0)) != 0:
    
        for i in range(int(os.environ.get('CONTENT_LENGTH', 0))):
            data += sys.stdin.read(1)