http链接转成https的链接的几种方法

ops/2025/3/10 2:10:58/
http://www.w3.org/2000/svg" style="display: none;">

以下是一个将HTTP链接转换为HTTPS的JavaScript函数,处理了多种常见输入情况:

function convertToHttps(url) {if (typeof url !== 'string') return url;// 移除首尾空格并处理空字符串const trimmedUrl = url.trim();if (!trimmedUrl) return 'https://';// 替换HTTP协议(不区分大小写)let converted = trimmedUrl.replace(/^http:\/\//i, 'https://');// 处理协议相对地址(以//开头)if (converted.startsWith('//')) {return 'https:' + converted;}// 处理无协议地址if (!/^https?:\/\//i.test(converted)) {// 处理类似 "example.com/path" 或 "www.example.com" 的情况return converted.startsWith('/') ? `https:/${converted}` : `https://${converted}`;}return converted;
}

功能说明:

  1. 协议转换

    • http://HTTP:// 转换为 https://
    • 保留已存在的 https:// 协议不变
  2. 协议相对地址处理

    • 输入 //example.com → 转换为 https://example.com
  3. 无协议地址处理

    • 输入 example.com → 转换为 https://example.com
    • 输入 /api/data → 转换为 https:///api/data(需根据业务场景调整)
  4. 特殊字符处理

    // 保留端口号和路径
    convertToHttps('http://example.com:8080/api?v=1') 
    // → "https://example.com:8080/api?v=1"// 处理用户认证信息
    convertToHttps('http://user:pass@example.com') 
    // → "https://user:pass@example.com"
    

测试用例:

// 基础转换
console.log(convertToHttps('http://example.com'));          // "https://example.com"
console.log(convertToHttps('https://secure.com'));         // "https://secure.com"
console.log(convertToHttps('HTTP://BIGSITE.COM'));         // "https://BIGSITE.COM"// 协议相对地址
console.log(convertToHttps('//cdn.example.com'));          // "https://cdn.example.com"// 无协议地址
console.log(convertToHttps('example.com/path'));           // "https://example.com/path"
console.log(convertToHttps('www.example.com'));            // "https://www.example.com"
console.log(convertToHttps('/api/data'));                 // "https:///api/data"// 特殊场景
console.log(convertToHttps('http://user:pass@site.com'));  // "https://user:pass@site.com"
console.log(convertToHttps('http://localhost:3000'));      // "https://localhost:3000"

增强建议:

  1. 域名白名单

    const WHITELIST = ['localhost', '127.0.0.1'];
    function shouldConvert(url) {const domain = new URL(url).hostname;return !WHITELIST.includes(domain);
    }
    
  2. 混合内容检测

    function hasMixedContent(pageUrl, resourceUrl) {const pageProtocol = new URL(pageUrl).protocol;const resProtocol = new URL(resourceUrl).protocol;return pageProtocol === 'https:' && resProtocol === 'http:';
    }
    
  3. 自动重定向处理

    async function secureFetch(url) {const secureUrl = convertToHttps(url);try {return await fetch(secureUrl);} catch (err) {if (err.message.includes('SSL')) {console.warn('回退到HTTP');return fetch(url.replace('https://', 'http://'));}throw err;}
    }
    

该函数可满足大多数场景的HTTP到HTTPS转换需求,建议根据具体业务场景调整协议回退策略和特殊域名处理逻辑。


http://www.ppmy.cn/ops/164538.html

相关文章

案例1_1:Proteus点亮8个蓝色LED灯

文章目录 文章介绍1、原理图2、新建项目文件和.c文件3、代码3.1 源码3.2 生成16进制.hex文件3.3 重建代码3.4 在代码路径中找到.hex文件 4、在原理图中加载代码5、效果图 文章介绍 用Proteus仿真图实现点亮8个led蓝色小灯 1、原理图 2、新建项目文件和.c文件 在STC89C52Study…

OLED屏幕开发全解析:从硬件设计到物联网显示实战 | 零基础入门STM32第五十二步

主题内容教学目的/扩展视频OLED显示屏重点课程电路原理,手册分析,驱动程序。初始化,清屏,ASCII字库,显示分区。调用显示函数。做带有加入图形和汉字显示的RTC时钟界面。讲字库的设计原理。 师从洋桃电子,杜…

C++——类与对象2

类的6个默认成员函数 C中,当类为空的时候(没有成员),编译器就什么都不做吗? 其实不是的,这时,编译器就会自动生成6个默认成员函数: 那么,什么是默认成员函数呢&#xf…

Python 智能机房签到系统:高效管理课堂考勤

智能机房签到系统:高效管理课堂考勤 相关资源文件已经打包成EXE文件,可双击直接运行程序,且文章末尾已附上相关源码,以供大家学习交流,博主主页还有更多Python相关程序案例,秉着开源精神的想法,…

UDP学习笔记(一)为什么UDP需要先将数据转换为字节数组

UDP 发送数据时需要先将数据转换为字节数组再发送,主要是因为计算机网络传输的最基本单位是“字节”(Byte)。让我们从以下几个方面来深入理解这个设计选择: 1. 计算机网络只能传输“字节” 在网络通信中,无论是 TCP 还…

ubuntu 20.04 C++ 源码编译 cuda版本 opencv4.5.0

前提条件是安装好了cuda和cudnn 点击下载: opencv_contrib4.5.0 opencv 4.5.0 解压重命名后 进入opencv目录,创建build目录 “CUDA_ARCH_BIN ?” 这里要根据显卡查询一下,我的cuda是11,显卡1650,所以是7.5 查询方法1&#xff1…

Windsuf 连接失败问题:[unavailable] unavailable: dial tcp...

问题描述 3月6日,在使用Windsuf 时,遇到以下网络连接错误: [unavailable] unavailable: dial tcp 35.223.238.178:443: connectex: A connection attempt failed because the connected party did not properly respond after a period of…

2025 年开源替代方案为何正在取代 OutSystems?技术自由度与成本优势深度解析

原文链接:https://www.nocobase.com/cn/blog/outsystems-open-source-alternatives OutSystems 的隐藏成本不只是金钱 OutSystems 是企业低代码开发领域的领军者。通过将生成式 AI 工具深度集成到软件生命周期,OutSystems 助力企业快速构建客户导向的门…