简体   繁体   中英

How To Send CORS Headers From Plain CGI/Python to Frontend

I have an Angular frontend running on localhost:4200 that has a http.post call like this:

let headers = new HttpHeaders();
headers.append('Content-Type', 'application/json');

return this.http.post<[]>('https://localhost/backend.py',new HttpParams().set("parameter1","4").set("parameter2","2022"));

and then my python file is like this, running on Apache, ie localhost:80:

#!/usr/bin/python
(import statements)

print("Access-Control-Allow-Origin: *")
print("Access-Control-Allow-Methods: POST, GET, OPTIONS")
print("Content-Type: text/html\n")

(rest of script)

Angular keeps throwing up the CORS error. I tried just printing them like the above because that's what a number of Google searches indicated to do, but it doesn't work, Angular keeps throwing up the error.

In php, you usually just output the headers at the beginning of the file and that takes care of it, but I don't know what to do here. Most of what I can find via searches is for flask/Django/etc as opposed to a plain python file.

I'm probably overlooking something simple.

Since you tagged your question with "cgi", I'm assuming that you are using the cgi.py library, about which, by the way, the documentation says, "Deprecated since version 3.11, will be removed in version 3.13"

So, this really isn't supported any more - you might want to think about using an actual python web framework. Also, this has absolutely nothing to do with Angular, so I removed that tag from your question and edited your title.

Anyway, the documentation also says that you need a blank line between the headers and the rest of the content, so you probably want:

#!/usr/bin/python
(import statements)

print("Access-Control-Allow-Origin: *")
print("Access-Control-Allow-Methods: POST, GET, OPTIONS")
print("Content-Type: text/html\n")
print() # add this

(rest of script)

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