简体   繁体   English

如何将 CORS 标头从普通 CGI/Python 发送到前端

[英]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:我有一个在 localhost:4200 上运行的 Angular 前端,它有一个 http.post 调用,如下所示:

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:然后我的python文件是这样的,运行在Apache,即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. Angular 不断抛出 CORS 错误。 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.我尝试像上面那样打印它们,因为这是许多谷歌搜索指示要做的,但它不起作用,Angular 不断抛出错误。

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.在 php 中,您通常只需 output 文件开头的标题即可,但我不知道在这里做什么。 Most of what I can find via searches is for flask/Django/etc as opposed to a plain python file.我可以通过搜索找到的大部分内容都是针对 flask/Django/etc 的,而不是普通的 python 文件。

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"由于您用“cgi”标记了您的问题,我假设您使用的是 cgi.py 库,顺便说一下,关于该库,文档说,“自 3.11 版以来已弃用,将在 3.13 版中删除”

So, this really isn't supported any more - you might want to think about using an actual python web framework.所以,这真的不再受支持了——你可能想考虑使用一个实际的 python web 框架。 Also, this has absolutely nothing to do with Angular, so I removed that tag from your question and edited your title.此外,这与 Angular 完全无关,因此我从您的问题中删除了该标签并编辑了您的标题。

Anyway, the documentation also says that you need a blank line between the headers and the rest of the content, so you probably want:无论如何,文档还说你需要在标题和内容的 rest 之间有一个空行,所以你可能想要:

#!/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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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