前端图片加载遇到 403?使用代理绕过 Hotlink 防盗链

🧩 背景

在做前端项目时,我们经常需要加载第三方网站的图片资源。例如在做电影列表展示时,你可能会加载豆瓣的图片地址:

<img src="https://img9.doubanio.com/view/photo/s_ratio_poster/public/p2641806535.jpg" />

这张图在浏览器地址栏中打开没问题,但一旦放进页面中,就出现了经典的错误:

Failed to load resource: the server responded with a status of 403 (Forbidden)

🔍 为什么会出现 403?

这是因为目标服务器(如豆瓣)开启了防盗链(Hotlink Protection)机制,会通过 Referer 判断你的网页是不是来自合法域名:

  • ✅ 在浏览器地址栏中访问:Referer 是空或自身域名 → 允许

  • ❌ 在你网站中 <img src="..."> 加载:Referer 是你自己的域名 → 403 拒绝

🛠️ 解决方案:用 Node.js + Express 代理图片请求

我们可以在服务端加一个 图片代理接口

  1. 前端通过 /proxy?url=xxx 请求我们自己的服务器

  2. 服务端再请求豆瓣服务器,并伪造 Referer 头部

  3. 把图片原样转发回浏览器

app.get('/proxy', async (req, res) => {
    const imageUrl = req.query.url
    console.log(imageUrl)
    const response = await fetch(imageUrl, {
        headers: {
            // 模拟 referer
            Referer: 'https://movie.douban.com'
        }
    })
    console.log(response)
    res.set('Content-Type', response.headers.get('content-type'))
    // 转换为 Node 可用的流并通过管道输出
    await pipeline(Readable.fromWeb(response.body), res)
})

 

posted @ 2025-06-05 08:19  PEAR2020  阅读(171)  评论(0)    收藏  举报