JavaScript 获取短链接原始地址的解决方案
📦 方法 1:服务器代理(推荐)
前端代码
javascript
async function getOriginalUrl(shortUrl) {
try {
const response = await fetch(`/api/unshorten?url=${encodeURIComponent(shortUrl)}`);
const data = await response.json();
return data.originalUrl;
} catch (error) {
console.error("获取失败:", error);
}
}
// 使用示例
getOriginalUrl("https://s.coze.cn/t/45uxprrK8vU/")
.then(original => console.log("原始链接:", original));
Node.js 服务器端代码
javascript
const express = require('express');
const axios = require('axios');
const app = express();
app.get('/api/unshorten', async (req, res) => {
const shortUrl = req.query.url;
try {
const response = await axios.head(shortUrl, { maxRedirects: 0 });
// 检测重定向状态码 (301/302)
if ([301, 302].includes(response.status)) {
res.json({ originalUrl: response.headers.location });
} else {
res.json({ originalUrl: shortUrl });
}
} catch (error) {
if (error.response?.status === 302 && error.response.headers.location) {
res.json({ originalUrl: error.response.headers.location });
} else {
res.status(500).json({ error: "解析失败" });
}
}
});
app.listen(3000, () => console.log('Server running on port 3000'));
优点:
- 避开浏览器 CORS 限制
- 完全可控
- 可添加缓存/安全验证
缺点:
- 需要搭建后端服务
🌐 方法 2:纯前端尝试(受限)
javascript
async function getOriginalUrl(shortUrl) {
try {
const response = await fetch(shortUrl, {
method: 'HEAD',
redirect: 'manual'
});
if ([301, 302].includes(response.status)) {
return response.headers.get('location');
}
return shortUrl;
} catch (error) {
console.error("请求失败:", error);
}
}
注意:
- 大多数短链接服务(如 s.coze.cn)会因 CORS 限制失败
- 仅适用于设置了
Access-Control-Allow-Origin
的服务
🔌 方法 3:使用第三方 API
javascript
async function getOriginalUrl(shortUrl) {
const API_KEY = "YOUR_API_KEY";
const apiUrl = `https://unshorten.me/api/v2/unshorten?url=${shortUrl}`;
try {
const response = await fetch(apiUrl, {
headers: { "Authorization": API_KEY }
});
const data = await response.json();
return data.resolved_url;
} catch (error) {
console.error("解析失败:", error);
}
}
常用服务:
- unshorten.me
- unshorten.io
- relink (需注册 API Key)
⚠️ 重要注意事项
- 浏览器限制:前端直接获取受 CORS 策略限制
- 安全风险 :
- 短链接可能指向恶意网站
- 建议服务器端进行安全验证
- 服务稳定性 :
- 短链接服务可能变更策略导致解析失效
- 建议添加错误处理和重试机制
- 性能优化 :
- 添加缓存机制(localStorage/服务器缓存)
- 避免频繁请求同一短链接
推荐方案:优先使用服务器代理方案(方法1),提供最大的灵活性和可控性