如何通过Node.js端Axios获取link.medium.com对应的Medium最终跳转URL
Node.js 中 Axios 解析 Medium 短链拿不到最终地址的解决方法
问题根因
- Medium短链的跳转链路分多层,
rsci.app.link节点返回的是200状态码的客户端跳转页(靠meta标签或JS触发跳转),并不是服务端返回的30x重定向。Axios默认的自动重定向机制只会跟踪服务端返回的30x状态跳转,遇到这类前端触发的跳转不会自动跟进,请求会直接停在中间页。 - 跳转链路会校验请求的
User-Agent字段,Axios在Node环境下默认的UA会被链路拦截,拿不到最终指向Medium正式文章的跳转。
实现方案
要拿到最终地址,核心要做两个调整:
- 给请求加上模拟真实浏览器的请求头,绕过UA校验
- 手动跟进整条跳转链路,同时处理服务端30x跳转、客户端meta/JS跳转两类场景
可直接复用的代码
const axios = require('axios'); const https = require('https'); async function resolveMediumShortLink(shortUrl) { // 模拟Chrome浏览器请求头,绕过跳转链路的UA校验 const requestHeaders = { 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36' }; let currentUrl = shortUrl; // 限制最大跳转层数,避免死循环 for (let jumpIndex = 0; jumpIndex < 10; jumpIndex++) { const response = await axios.get(currentUrl, { headers: requestHeaders, // 关闭Axios自动重定向,手动处理跳转逻辑 maxRedirects: 0, // 所有状态码都不抛出请求错误 validateStatus: () => true, httpsAgent: new https.Agent({ rejectUnauthorized: false }) }); // 优先处理服务端返回的30x重定向 if ([301, 302, 303, 307, 308].includes(response.status)) { currentUrl = response.headers.location; continue; } // 解析HTML里的客户端跳转地址 const htmlContent = response.data; // 匹配meta refresh标签的跳转地址 const metaJumpMatch = htmlContent.match(/<meta[^>]+http-equiv="refresh"[^>]+url=([^>"']+)/i); // 匹配JS里的location跳转地址 const jsJumpMatch = htmlContent.match(/(?:window\.location\.href|location\.replace)\s*=\s*['"]([^'"]+)['"]/i); const jumpTarget = metaJumpMatch?.[1] || jsJumpMatch?.[1]; if (jumpTarget) { // 处理相对路径,拼接成完整URL currentUrl = new URL(jumpTarget, currentUrl).href; // 命中Medium正式域名直接返回 if (currentUrl.includes('medium.com/')) { return currentUrl; } continue; } // 没有找到后续跳转,说明已经到最终页面,直接返回 return currentUrl; } throw new Error('超过最大跳转层数,无法解析短链最终地址'); } // 调用示例 const finalUrl = await resolveMediumShortLink('https://link.medium.com/C1hxgiphAcb'); console.log(finalUrl);
原有代码的不足
- 没有配置模拟浏览器的
User-Agent,触发跳转链路的拦截规则,请求仅能跳转到中间页 - 依赖Axios内置的自动重定向能力,没有处理前端触发的客户端跳转逻辑,无法跟进到最终地址
- 读取
mediumRequest.request.res.responseUrl得到的只是Axios最后一次自动跟进的跳转地址,也就是第一个302指向的中间页地址,根本不是链路的最终落点。
内容的提问来源于stack exchange,提问作者Satya Kalluri
相关产品推荐
相关产品推荐

