如何在 HTTPS 上强制从前端 运行 发出 HTTP 请求?

How to force to make HTTP requests from a frontend running on HTTPS?

我在本地 HTTPS 上有一个前端 运行,并带有本地证书。我想访问 HTTP 上的本地后端。

我将元标记添加到我的 index.html 以允许这样做:

<meta http-equiv="Content-Security-Policy" content="upgrade-insecure-requests">

...但是 axios 拒绝这样做:

        axios({
            method: 'post',
            baseURL: 'http://localhost:3000',
            url: '/test',
            data: {
                firstName: 'Will',
                lastName: 'Smith'
            }
        }).then((result) => {
            console.log('done!');
        }

请注意,我明确地将 http 添加到 baseUrl。不过,我明白了:

POST https://localhost:3000/test net::ERR_SSL_PROTOCOL_ERROR

axios 仍然通过 https 发送。

我试过使用 fetch:

       fetch('http://localhost:3000/test', {
            method : "POST",
            body: JSON.stringify({
                firstName: 'Finn',
                lastName: 'Williams'
            }),
        }).then((response) => {
            console.log('done! ' + response.json());
        ).catch((error) => {
            console.log('error');
        });

最后是一个原始的 XMLHttpRequest 请求:

        const http = new XMLHttpRequest();

        http.open("POST", 'http://localhost:3000/test', true);

        // Call a function when the state
        http.onreadystatechange = function () {
            if (http.readyState == 4 && http.status == 200) {
                alert(http.responseText);
            }
        }
        http.send(JSON.stringify({
            firstName: 'Finn',
            lastName: 'Williams'
        }));

但每次浏览器似乎切换到 HTTPS 时都会失败并出现同样的错误。

有可能做到这一点吗?

由于Same origin policy,这是不可能的。或者您可以使用服务器端解决方案将 https 请求重定向到 http。