为什么前端发出的http请求变成了https协议?

原因分析

http变成了https,那么肯定是和安全相关的缘故导致的,因此我们只需要排查下对应的配置项即可。

另外由于请求是客户端发起的,所以代码一定是和前端/浏览器相关的,我们需要把排查范围缩小到HTML、JS和浏览器设置上。

案例

axios的withCredentials配置导致前端发出的请求协议全部变成https的问题

前端代码里面写的请求后端接口的地址是http协议的,但是真正发出去的时候,变成了https协议。查看Chrome控制台,有如下报错:

1
header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.

我们是用axios发起请求的,从这个报错来看,源自XMLHttpRequest对象的withCredentials属性,那么肯定就是我们给axios配置了这个属性为true了。查看axios的API,果然有这么一项,修改过来即可。

参考资料:

Reason: Credential is not supported if the CORS header ‘Access-Control-Allow-Origin’ is ‘*’:

https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS/Errors/CORSNotSupportingCredentials

axios的API:

https://github.com/axios/axios#axios-api

Access-Control-Allow-Credentials:

https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Credentials

upgrade-insecure-requests

继上一个http请求变成https的问题,我们修改之后,发现仍然还是会出现页面中的http请求变成https的问题。由于请求是客户端发出来的,所以肯定这是前端相关的代码导致的;而JS中请求发送的内容已经处理了,那么我猜测是否是我们的HTML代码做了什么设置,导致页面发出的请求协议被修改了呢?

查看页面的HTML代码,发现了如下meta头,设置了Content-Security-Policy

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

该配置将安全策略设置为了upgrade-insecure-requests,即自动将网页上所有加载外部资源的 HTTP 链接换成 HTTPS 协议。

因此去掉该设置即可。