HTTP 到 https 重定向被 CORS 策略阻止

Http to https redirect blocked by CORS policy

我正在尝试从 chrome 开发人员工具控制台 window 运行ning 在一个网站上向本地主机服务器发出 GET(或 POST)请求https(在本例中 outlook.com,但对于任何 https 都是一样的)。如果我 运行 来自 http 上 运行ning 网站的相同代码,它工作正常。

我遇到的错误:

Failed to load http://127.0.0.1:5000/: Redirect from 'http://127.0.0.1:5000/' to 'https://127.0.0.1:5000/' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://outlook.live.com' is therefore not allowed access.

我发现 https 到 http 的通信是不可能的,但是 运行在 https 上安装 flask 服务器也无济于事,在这种情况下 Flask 甚至无法识别传入的请求。

我有一个 Flask 应用程序 运行ning,代码:

from flask import Flask
from flask import request
from flask_cors import CORS

app = Flask(__name__)

CORS(app)

@app.route("/", methods=['GET', 'POST'])
def foo():
    return "bar"


if __name__ == "__main__":
    app.run()

我用于请求的javascript:

var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        console.log(xhttp.responseText);
    }
};
xhttp.open("GET", "http://127.0.0.1:5000/", true);
xhttp.send();

我知道有很多类似的问题,但是 none 已发布的解决方案对我有用,如何创建成功的 GET 或 chrome 开发人员的 POST 请求工具 运行在 https 网站上连接到本地主机服务器(最好是 Flask)?

当 运行 Flask 应用 ssl_context='adhoc' 使用 https:

是浏览器阻止了https,因为证书不安全。

这个答案(发布 here)对我有用:

NOT FOR PROD

Simply paste this in your chrome:

chrome://flags/#allow-insecure-localhost You should see highlighted text saying: Allow invalid certificates for resources loaded from localhost

Click Enable.

此外,this blog post 详细说明了如何使用带有证书的 Flask。