简体   繁体   中英

Returning JSON data from Apache cgi-bin Python script

I am trying to return JSON data from a Python CGI script running on a local Apache server (xampp).

The script itself runs fine with no issues and the expected result is returned, however despite the script outputting the header

print("Content-type: application/json; charset: utf-8")

when an AJAX request is made (from a client-side javascript) to the same script, the request fails. After running

#!C:\Python39\python.exe -u
import cgi

cgi.test()
exit(0)

It turns out the accepted response headers under the Shell Environment: section are as follows

HTTP_ACCEPT
 text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9

This is causing the JSON response to be sent as HTML, which is breaking the request, since the response is sent in JSON but the request only accepts responding with HTML.

I tried fixing this by adding the accepted MIME type in the .htaccess file within the /cgi-bin directory with

AddType application/json .py

But this doesn't work and I don't expect forcing my.py script to be interpreted as a.json file to be the desired solution, since I want the output as JSON, not the file itself.

The Apache documentation here claims non-html content can be sent but it does not give an example on how to accomplish this.

I also have many PHP files (in /htdocs ) in my project which do the exact same thing (outputting a JSON response which is accessed via an external AJAX request) however, beyond simply outputting the JSON header in the script, they do not require any modification to the server's accepted output and work properly without any further intervention.

I can't seem to find any other solutions related to forcing the server to respond with JSON data instead of HTML text for CGI scripts.

After some investigation, it turns out this was a CORS issue and not a conflict with the accepted Content-type and the fact that calling

cgi.test()

Only outputs HTML headers, regardless of whatever the expected server response should be.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM