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

问题描述

我有一个使用本地证书在 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。