如何将域名转换为完整URL?无法预先确定HTTP/HTTPS协议
域名转完整URL(自动识别HTTP/HTTPS)
你的代码逻辑存在问题:拼接https://和域名的操作不会抛出任何异常,所以catch分支永远不会执行,相当于永远只会用HTTPS,根本没实现降级到HTTP的逻辑。
下面分两种场景给出可行的解决方案:
Node.js 环境
可以通过发起网络请求尝试连接,优先试HTTPS,失败则降级到HTTP:
const http = require('http'); const https = require('https'); function getFullUrl(domain) { return new Promise((resolve) => { // 先尝试HTTPS const httpsReq = https.get(`https://${domain}`, (res) => { // 处理重定向(比如google.com会跳转到www.google.com) const finalUrl = res.headers.location || `https://${domain}/`; resolve(finalUrl); httpsReq.destroy(); }).on('error', () => { // HTTPS失败,尝试HTTP const httpReq = http.get(`http://${domain}`, (res) => { const finalUrl = res.headers.location || `http://${domain}/`; resolve(finalUrl); httpReq.destroy(); }).on('error', () => { // 两者都失败,返回默认值 resolve(`http://${domain}/`); }); }); }); } // 使用示例 getFullUrl('discord.com').then(url => console.log(url)); getFullUrl('google.com').then(url => console.log(url));
浏览器前端环境
由于浏览器跨域限制,直接发起AJAX请求可能失败,可通过尝试加载站点图标这类资源来判断协议:
async function getFullUrl(domain) { return new Promise((resolve) => { // 先试HTTPS const img = new Image(); img.src = `https://${domain}/favicon.ico`; img.onload = () => resolve(`https://${domain}/`); img.onerror = () => { // HTTPS失败,试HTTP const imgHttp = new Image(); imgHttp.src = `http://${domain}/favicon.ico`; imgHttp.onload = () => resolve(`http://${domain}/`); imgHttp.onerror = () => { // 都失败,返回HTTPS默认值 resolve(`https://${domain}/`); }; }; }); } // 使用示例 getFullUrl('discord.com').then(url => console.log(url));
补充说明
- 部分域名会自动重定向到带www的地址(比如google.com→www.google.com),Node.js环境可通过响应的
location头获取最终URL;前端若允许跳转页面,也可通过window.location获取。 - 若为内部系统域名,可直接约定使用HTTPS,避免额外的请求开销。
内容的提问来源于stack exchange,提问作者isaac
相关产品推荐
相关产品推荐

